Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 数组返回错误的值laravel_Php_Arrays_Ajax_Class_Laravel - Fatal编程技术网

Php 数组返回错误的值laravel

Php 数组返回错误的值laravel,php,arrays,ajax,class,laravel,Php,Arrays,Ajax,Class,Laravel,我发出一个ajax请求,响应是一个图像数组,问题是我回显了数组的值和我想要的值,但是当foreach结束时,我看到数组中的每个值都被数组的最后一项更改了 foreach ($x as $y) { $auxImg->misc_id = $y->misc_id; $auxImg->image = $y->image; $aux[$i] = $auxImg; echo $aux[$i]->image.' '

我发出一个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();

(取决于循环前使用的代码)

之后:

foreach ($x as $y) {

以获得预期的结果。

谢谢,它确实起了作用,但我仍然不明白为什么它在循环上显示不同的值,而在外部显示相同的值?这是因为PHP中的对象没有被复制,所以在循环内部,当你赋值时,你会看到这个值,但在循环之后,你会看到相同的值。您可以将其与:
$x=new stdClass()$x->a=5;echo$x->a$y=x美元$y->a=10;回声$y->a;echo$x->a要复制对象时,需要使用
克隆
foreach ($x as $y) {