如何在没有push_array的情况下将新元素插入到多维数组中


How to insert new Elements into a multidimensional array without push_array?

由于我想用谷歌图表库绘制一些温度图,我正在用PHP构建一个数组,以将其编码为JSON,如中所述

https://developers.google.com/chart/interactive/docs/reference#methods

"dataTable['cols']"的第一个条目是x轴。然后我想一一添加更多行。

这有效:

$dataTable = array();
$dataTable['cols'] = array(
    array('id' => 'time_axis', 'label' => 'Time', 'type' => 'datetime')
);
foreach($sensors as $id => $description) {
//Entries in $sensors are from a database
    $column = array('id' => $id, 'label' => $description, 'type' => 'number');
    array_push($dataTable['cols'],$column);
}

这不会(500 服务器错误):

$dataTable = array();
$dataTable['cols'] = array(
    array('id' => 'time_axis', 'label' => 'Time', 'type' => 'datetime')
);
foreach($sensors as $id => $description) {
//Entries in $sensors are from a database
    $column = array('id' => $id, 'label' => $description, 'type' => 'number');
    $dataTable['cols'][] = $column;
}

当我在这里阅读接受的答案时

PHP 使用array_push将元素添加到多维数组中

对,应该是等效的。

只需尝试以相同的方式添加x轴:

$dataTable['cols'][] = array('id' => 'time_axis', 'label' => 'Time', 'type' => 'datetime');

别忘了dataTable面前的$

foreach($items as $index => $array)
{ 
 $items[$index]['id']=$id; 
}

试试这个。