PHP-FOR循环中的帮助
我有一个数组,通过它循环并使用for循环推送数据PHP-FOR循环中的帮助,php,arrays,function,postgresql,output,Php,Arrays,Function,Postgresql,Output,我有一个数组,通过它循环并使用for循环推送数据 $test_data = [10,20,35,01,50,60,87,12,45,86,9,85]; 实际上,这是一个样本数据。但我的数据与我从PostgreSQL中获得的结果类似,这是一个单列数据 对$test_数据使用以下函数 即使在这里,我也只能得到浏览器中的最后一行——echo json_encode$data 类似于我上面提到的结果 前9行未插入数据[]。只有最后一行被添加到数组中 请告诉我我在哪里犯错 提前感谢。因为数组不能具有与索
$test_data = [10,20,35,01,50,60,87,12,45,86,9,85];
实际上,这是一个样本数据。但我的数据与我从PostgreSQL中获得的结果类似,这是一个单列数据
对$test_数据使用以下函数
即使在这里,我也只能得到浏览器中的最后一行——echo json_encode$data
类似于我上面提到的结果
前9行未插入数据[]。只有最后一行被添加到数组中
请告诉我我在哪里犯错
提前感谢。因为数组不能具有与索引相同的键 您需要将其改写为
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'][] = $test_data[$x];
// ^^ <--- Add that.
}
您可以在不使用pg_num_行的情况下执行此操作:
非常感谢:接受答案需要12分钟。如果您想以$fetch_data形式在简单数组上迭代,请使用foreach
for( $x=0; $x < pg_num_rows($query); $x++ ) {
$data['data1'] = pg_fetch_assoc($query);
}
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'][] = $test_data[$x];
// ^^ <--- Add that.
}
foreach($test_data as $val)
{
$chart_data['data1'][] = $val;
}
// 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;
}