2017-06-21 195 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