PHP - 帮助FOR LOOP

时间:2014-04-29 08:37:20

标签: php arrays function postgresql output

我有一个数组并循环遍历它并使用for循环推送数据。

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

实际上这是一个样本数据。但我的数据结果类似于我从PostgreSQL获得的结果,这是一个单列数据。

使用$test_data的以下功能。

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

结果: {"data1":{"data": 85"}}

这是我在PHP中使用PostgreSQL结果时使用的for循环。

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

即使在这里,我只会在浏览器中获得最后一行 - echo json_encode($data);

与我上面提到的结果类似的内容。

前9行未插入data[]。只有最后一行被添加到数组中。

请告诉我我在哪里做错了。

提前致谢。

2 个答案:

答案 0 :(得分:6)

由于数组不能与索引具有相同的密钥。

您需要将其重写为..

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

Loic 建议使用foreach时,我快速回答,所以它首先没有打击我的想法

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

答案 1 :(得分:2)

你可以这样做(不使用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;
}