"xxx", 'val2' => 0, 'val3' => 0 ]; 然后在我的 m-6ren">
gpt4 book ai didi

PHP MySQLi fetch "array push"覆盖数据

转载 作者:可可西里 更新时间:2023-11-01 08:28:35 25 4
gpt4 key购买 nike

我有 2 个数组:

$arr = [];

$tempArray = [
'val1' => "xxx",
'val2' => 0,
'val3' => 0
];

然后在我的 mysql 查询中,我用当前行的值填充临时数组,最后将他插入 $arr:

$stmt->bind_result($tempArray["val1"], $tempArray["val2"], $tempArray["val3"]);

while ( $stmt->fetch () ) {
array_push($arr, $tempArray);
}

问题是,在每个循环中,“array_push”都会覆盖 $arr 中的数据。

例如,我在 $stmt->fetch() 中循环了 3 次。

<强>1。循环

$tempArray = [
'val1' => "Hello",
'val2' => 1,
'val3' => 2
]

$arr = [
0 = [
'val1' => "Hello",
'val2' => 1,
'val3' => 2
];
]

<强>2。循环

$tempArray = [
'val1' => "Stack",
'val2' => 3,
'val3' => 4
]

$arr = [
0 = [
'val1' => "Stack",
'val2' => 3,
'val3' => 4
],
1 = [
'val1' => "Stack",
'val2' => 3,
'val3' => 4
];
]

<强>3。循环

$tempArray = [
'val1' => "Overflow",
'val2' => 5,
'val3' => 6
]

$arr = [
0 = [
'val1' => "Overflow",
'val2' => 5,
'val3' => 6
],
1 = [
'val1' => "Overflow",
'val2' => 5,
'val3' => 6
],
2 = [
'val1' => "Overflow",
'val2' => 5,
'val3' => 6
]
]

我以前从未见过这种行为,我也不知道为什么会这样。

最后我想要的是这样的:

$arr = [
0 = [
'val1' => "Hello",
'val2' => 1,
'val3' => 2
],
1 = [
'val1' => "Stack",
'val2' => 3,
'val3' => 4
],
2 = [
'val1' => "Overflow",
'val2' => 5,
'val3' => 6
]
]

$stmt 类(@Stevish 请求)

$query = "...";
if ( $stmt = $this->db->prepare($query)) {
$stmt->bind_param('i', $xxx);
$stmt->execute();
$stmt->store_result();
$$stmt->bind_result($tempArray["val1"], $tempArray["val2"], $tempArray["val3"]);
while ( $stmt->fetch () ) {
$arr[] = $tempArr;
}
}

最佳答案

问题是您将对 $tempArray 的引用插入到 $arr 中。然后你改变引用。在第三个循环中,您有 3 个对同一个数组的引用。这就是值以这种方式显示的原因……您可以用一种相当不直观的方式解决这个问题。

尝试:

$stmt->bind_result($tempArray["val1"], $tempArray["val2"],$tempArray["val3"]);
while ( $stmt->fetch () ) {
$x = $tempArray; //This copies the values of $tempArray to $x and each loop will create a new x.
array_push($arr, $x);
}

关于PHP MySQLi fetch "array push"覆盖数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com