【问题标题】:PHP - Help in FOR LOOPPHP - FOR LOOP 中的帮助
【发布时间】:2014-06-15 02:12:22
【问题描述】:

我有一个数组并循环遍历它并使用 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[] 中。只有最后一行被添加到数组中。

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

提前致谢。

【问题讨论】:

  • 如果你想迭代一个简单的数组(如$fetch_data)使用foreach()

标签: php arrays function postgresql output


【解决方案1】:

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

你需要将它重写为..

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

【讨论】:

  • 非常感谢 :) 再等 12 分钟接受答案。
【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2016-09-08
    相关资源
    最近更新 更多