0

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.

1
  • if you want to iterate on a simple array (as $fetch_data) use foreach() Commented Apr 29, 2014 at 8:44

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot :) More 12 minutes to accept the answer.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.