【问题标题】:How to insert new Elements into a multidimensional array without push_array?如何在没有 push_array 的情况下将新元素插入多维数组?
【发布时间】:2016-07-06 23:08:21
【问题描述】:

由于我想使用 Google 图表库绘制一些温度图,因此我正在 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 add elements to multidimensional array with array_push

对,应该是等价的。

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案1】:

    试着用同样的方法添加你的 x 轴:

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

    别忘了dataTable前面的$

    【讨论】:

    • 是的,谢谢,现在可以了。你能解释一下为什么这会有所不同吗?
    • 我不确定,但我认为这是因为 PHP 使用第一种语法创建了一个“静态”数组,并为他的内容分配了适量的内存。所以,当你想在里面添加一些东西时,你必须通过array_push() 告诉它,因为 PHP 需要重新分配内存。我猜另一种语法只是打开一种缓冲区,您可以随时放置您想要的东西。也许这些记忆技巧在文档中进行了解释。希望对您有所帮助!
    • 看看链表:en.wikipedia.org/wiki/Linked_list也许第二种语法使用它们并解释你的问题!
    【解决方案2】:
    foreach($items as $index => $array)
    { 
     $items[$index]['id']=$id; 
    }
    

    试试这个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2012-07-21
      • 2022-01-12
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      相关资源
      最近更新 更多