Question

I have an array and looping through it and pushing the data using for loop.

$test_data = [10,20,35,01,50,60,87,12,45,86,9,85];

Actually that's a sample data. But my data is a result similar to that which I get from PostgreSQL, a single column data.

Using the below function for $test_data.

for( $x=0; $x < 12; $x++ ) {
    $chart_data['data1'] = $test_data[$x];
}

Result : {"data1":{"data": 85"}}

Here's the for loop which I use along the PostgreSQL result in the PHP.

for( $x=0; $x < pg_num_rows($query); $x++ ) {
    $data['data1'] = pg_fetch_assoc($query);
}

Even here I get only the last row in the browser when I do - echo json_encode($data);

Something similar to the result what I've mentioned above.

First 9 rows are not getting inserted into the data[]. Only the last row is getting added to the array.

Please say me where I'm doing the mistake.

Thanks in advance.

Was it helpful?

Solution

Since arrays cannot have same key as index.

You need to rewrite it as ..

for( $x=0; $x < 12; $x++ ) {
    $chart_data['data1'][] = $test_data[$x];
    //                  ^^ <--- Add that.
}

As Loic suggested go with a foreach , I answered quickly so it didn't strike on my mind in the first place

foreach($test_data as $val)
{
 $chart_data['data1'][] = $val;
}

OTHER TIPS

You could do like this (without using pg_num_rows):

// better initialize the result array
$data = array('data1' => array());

while ($row = pg_fetch_assoc($query)) {
  // here is the point, add element to the array
  $data['data1'][] = $row;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top