0

As I want to plot some temperature graphs with the Google Chart Library I am building an Array in PHP to encode it to JSON as described in

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

The first entry of "dataTable['cols']" is the x-axis. I then want to add some more lines one by one.

This works:

$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);
}

This does not (500 Server Error):

$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;
}

When I'm reading the accepted answer here

PHP add elements to multidimensional array with array_push

right, it should be equivalent.

JHnet
  • 461
  • 6
  • 18

2 Answers2

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

Try this.

0

Just try to add your x-axis with the same way :

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

And don't forget the $ in front of dataTable !

Antoine Bellion
  • 136
  • 1
  • 9
  • Yeah thanks, that works now. Can you explain why this makes a difference ? – JHnet Mar 20 '16 at 13:32
  • I'm not sure, but I think it's because PHP create a 'static' array with the first syntax and allocate the right amount of memory for his content. So, when you want to add something inside, you have to tell it via `array_push()` because PHP need to re-allocate memory. I guess the other syntax just open a sort of buffer whitch you can put what you want on the fly. Maybe these memory trick are explained in the doc. Hope this help ! – Antoine Bellion Mar 20 '16 at 13:43
  • Take a look at the linked list : https://en.wikipedia.org/wiki/Linked_list Maybe the second syntax use them and explain your question ! – Antoine Bellion Mar 20 '16 at 13:51