将 MySQLi 动态数据推送到数组中会失败,而其他一切都会成功


Pushing MySQLi dynamic data into an array fails while everything else succeeds

我有以下代码来动态分配来自MySQL数据库的结果(假设之前的所有代码都是正确的 - 因为我这样做)

// Execute the query.
$statement->execute();
// Grab the dynamic number of results.
$statement->store_result();
$meta = $statement->result_metadata();
$data = array();
$refs = array();
while ($name = $meta->fetch_field()) {
  $refs[] =& $data[$name->name];
} // while ($name = $meta->fetch_field())
$meta->free_result();
call_user_func_array(array($statement, "bind_result"), $refs);

一旦我执行while ($statement->fetch()),就会出现问题。

以下代码将打印唯一数据(称为"打印机")

while ($statement->fetch()) {
  print print_r($data, true);
} // while ($statement->fetch())

但是,以下内容将仅打印最后一个数据库结果,$statement->num_rows次数(称为"推送器")

$array = array();
while ($statement->fetch()) {
  array_push($array, $data);
} // while ($statement->fetch())
print print_r($array, true);

在执行以下操作时模拟此 StackOverflow 问题给出的答案将返回与"推送器"while循环相同的结果。

$array = array();
while ($statement->fetch()) {
  $temp = $data;
  array_push($array, $temp);
} // while ($statement->fetch())
print print_r($array, true);

我的问题是,在"pusher"循环中,为什么我的所有数据都被覆盖,即使在每个循环开始时创建一个新变量,以及我如何在不执行类似 array_push($array, array("param1" => $data["param1"], "param2" => $data["param2"], ... "paramN" => $data["paramN"]))

执行以下行时,不绑定数组,而是绑定该数组的元素。

call_user_func_array(array($statement, "bind_result"), $refs);

这只是一种动态的方式

$statement->bind_result($data['x'], $data['y'], ...);

相当于:

$statement->bind_result($x, $y, ...);
数组

不是引用,但数组的所有元素都是引用。 var_dump($data)显示:

array(2) {
  ["category_name"]=>
  &NULL
  ["id"]=>
  &NULL
}

将此数组推送到新数组中时,不会推送值,而是推送引用。然后,您的$array数组由许多指向内存中相同值的数组组成。

我在另一个答案中谈到了这个问题,但解决方案是使用 get_result() 或取消引用值。

您可以通过while循环中的简单循环来执行此操作。在foreach循环的每次迭代中,PHP 将为该值创建一个新的 zval 容器。然后,您可以将该值推送到临时数组中,稍后再将其推送到 $array 中。

while ($statement->fetch()) {
    $temp = [];
    foreach ($data as $key => $val) {
        $temp[$key] = $val;
    }
    $array[] = $temp;
}