我正在尝试将数组复制到PHP中的另一个数组中。然后将响应作为JSON输出发送。但它只复制数组中的最后一个元素多次。请告诉我哪里出错了?任何帮助表示赞赏
PHP代码
stmt_bind_assoc($stmt, $resultrow);
while ($stmt->fetch()) {
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
print_r($resultrow)
的输出。这是正确的。数组中的值是不同的
Array( [a_id] => 1 [b_number] => 10101010 [dateandtime] => 2013-12-25 09:30:00 )
Array( [a_id] => 1 [b_number] => 20202020 [dateandtime] => 2013-12-27 11:40:00 )
json_encode($ r)的输出。这是不正确的。数组中的值是相同的
[{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"},
{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"}]
答案 0 :(得分:2)
你从这里得到了stmt_bind_assoc
函数:http://www.php.net/manual/en/mysqli-stmt.fetch.php#82742
发布在OP下面是:
“...问题是返回的$行是引用而不是数据。 因此,当你编写$ array [] = $ row时,$ array将被填充 数据集的最后一个元素。“
通过该用户的解决方案,我想出了解决您问题的方法:
// replace your posted code with the following
$r = array();
// loop through all result rows
while ( $stmt->fetch() ) {
$resultrow = array();
foreach( $row as $key=>$value )
$resultrow[ $key ] = $value;
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
下次从源代码获取代码时,请阅读有关源代码的注释。