2017-06-21 117 views
0

我正在將MySQL查詢中的數據提取到私有$ this - > _ data中。
但我也從另一個表填充數據到$ this - > _ data。

有沒有更簡單的方法來做到這一點?將關聯數組推送到現有的關聯數組

$this->_data = $row; # This fetches data from a MySQL query 

# This works 
$this->_data['Salary'] = ''; 
. 
. 
. 
$this->_data['Growth'] = ''; 

# This doesn't. Give s Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ']' 
$this->_data['Salary' => '', 
      . 
      . 
      . 
      'Growth' => '' 
      ]; 
+0

的最後一個例子是,你會用它來初始化一個新的數組的語法,但'_data'在這一點上已經初始化關聯數組可以是簡單定義。然後,您只能像前兩個示例一樣訪問各個元素。 – domsson

+0

不能覆蓋。 – PlanBuildr

回答

0

您是否在尋找array_merge()

$this->_data = $row; 
// ... 
$this->_data = array_merge($this->_data, [ 
    'Salary' => '', 
    // ... 
    'Growth' => '', 
]); 

如果不想合併的結果,你可以讓他們在一個多維數組

$this->_data[] = $row; 
$this->_data[] = [ 
    'Salary' => '', 
    // ... 
    'Growth' => '', 
]; 

echo $this->_data[0]['Salary']; // This came from the first query 
echo $this->_data[1]['Salary']; // This came from the second one 
0

一旦數據通過

檢索

如下

$this->_data = ['Salary' => '', ... 'Growth' => ''];

+0

$ this - > _ data = []覆蓋數據。 – PlanBuildr