Paul Paul - 9 months ago 47
PHP Question

Creating a correct PHP array

I am having difficulty looping to create a test array (before using similar approach to loop through a recordset). This PHP code does not work:-

$dataSet1 = array();
$dataSet1['label'] = 'Customer 1';

for ($i = 0; $i < 3; ++$i) {
$dataSet1['data'] = array($i,$i);

echo json_encode($dataSet1);

It only produces last value for data, not 3 data pairs:-

{"label":"Customer 1","data":[2,2]}

Where am I going wrong? I have googled, tried array_push, but no luck. Thanks.


You keep overwriting the value for $dataSet1['data'] in your loop.

If you want to append to an array, you can use this syntax:

$dataSet1['data'][] = array($i, $i); 

Or, you can use the array_push() function:

array_push($dataSet['data'], array($i, $i));