将foreach推送到foreach数组

时间:2018-09-19 12:13:19

标签: php laravel loops foreach

不确定如何放置标题,但是我在Laravel中有以下foreach:

foreach ($properties as $key => $property) {
            $data['items'][$key] = [
                'id' => $property->id,
                'street' => $property->street,
                'zipcode' => $property->zipcode,
                'city' => $property->city->name,
                'type' => $property->type->name,
                'interior' => $property->interior->type,
                'bedrooms' => $property->bedrooms,
                'year' => $property->year,
                'surface' => $property->surface,
                'available' => $property->available,
                'rent' => $property->rent,
                'service_costs' => $property->service_costs,
                'deposit' => $property->deposit,
                'text_nl' => $property->leader_text,
                'office' => $property->office->name,
                'images' => [

                    // all images for the current property here!

                ],
            ];


   }

我还需要遍历“图像”,因为一个属性可以包含多个图像。不幸的是,下面的代码不起作用,它只是附加了最后一个属性的图像。

foreach ($property->property_images as $key => $image) {

            $data['items']['images'][$key] = [

                'id' => $image->id,
            ];

        }

我已经尝试过使用array_map进行某些操作,但是无法弄清楚。请问对此有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

将此lb添加到您的第一个foreach()

foreach()

所以代码必须是:-

foreach ($property->property_images as $image) {// remove $key from here,not needed
        $data['items'][$key]['images'][] = [
            'id' => $image->id,
        ];
    }