简体   繁体   English

数组返回错误值laravel

[英]array return wrong value laravel

I make an ajax request and the response its an array of images, the problem is that i echo the value of the array and its the one that i want, but when the foreach ends and i see what have the array every value its changed by the last item of the array 我发出一个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"
  }
}

i really cant understand why this happend, that is the only time i use $aux var please help 我真的不明白为什么会这样,那是我唯一使用$ aux var的时候,请帮忙

The problem here is that $auxImg is all the time the same object, so in each step you modify this object and append it to array but because $auxImg is an object it's not copied. 这里的问题是$auxImg是同一对象,因此在每个步骤中,您都需要修改该对象并将其附加到数组中,但是由于$auxImg是一个对象,因此不会被复制。

You should add 您应该添加

$auxImg = new stdClass();

or 要么

$auxImg = clone $auxImg;

(depending what code you use before loop) (取决于循环之前使用的代码)

after: 后:

foreach ($x as $y) {

to get expected result. 获得预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM