[英]array return wrong value laravel
我發出一個ajax請求,響應是一個圖像數組,問題是我回顯了數組的值及其所需的值,但是當foreach結束時,我看到數組的每個值都被改變了數組的最后一項
foreach ($x as $y) {
$auxImg->misc_id = $y->misc_id;
$auxImg->image = $y->image;
$aux[$i] = $auxImg;
echo $aux[$i]->image.' ';
//response of the array in the echo
/* 5/maqueta.png - 5/ponto.png - 5/ciades.jpg - 5/35235.jpg */
$i++;
}
echo var_dump($aux);
//response in the var_dump of the aux array
array(4) {
[0]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
[1]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
[2]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
[3]=>
object(stdClass)#400 (2) {
["misc_id"]=>
int(9)
["image"]=>
string(11) "5/35235.jpg"
}
}
我真的不明白為什么會這樣,那是我唯一使用$ aux var的時候,請幫忙
這里的問題是$auxImg
是同一對象,因此在每個步驟中,您都需要修改該對象並將其附加到數組中,但是由於$auxImg
是一個對象,因此不會被復制。
您應該添加
$auxImg = new stdClass();
要么
$auxImg = clone $auxImg;
(取決於循環之前使用的代碼)
后:
foreach ($x as $y) {
獲得預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.