如何在嵌套集合中过滤?

时间:2017-05-12 23:09:11

标签: php laravel collections

Hello StackOverflow社区,我正在使用laravel,我创建了这个集合

$headquarters = collect([
        [
            'headquarter' => 'Leon',
            'offers' => [
                [
                    'name' => 'Name1',
                    'slug' => 'Name1'
                ], [
                    'name' => 'Name2',
                    'slug' => 'Name2'
                ]
            ]
        ],[
            'headquarter' => 'Granada',
            'offers' => [
                [
                    'name' => 'Name3',
                    'slug' => 'Name3'
                ],[
                    'name' => 'Name4',
                    'slug' => 'Name4'
                ],[
                    'name' => 'Name5',
                    'slug' => 'Name5'
                ]
            ]
        ]
    ]);

我想通过总部过滤此系列并提供slug以获得单一优惠

现在我正在尝试使用过滤器

 $offer = $this->headquarters()
        ->filter(function($hq) use ($headquarter, $slug) {
            return $hq['headquarter'] == $headquarter && $hq['offers']['slug'] == $slug;
        });

但没有成功。

感谢您的任何建议

2 个答案:

答案 0 :(得分:2)

您可以使用此代码获取特定总部的所有优惠

$this->headquarters()->where('headquarter', 'Leon')[0]['offers'][0];

然后为每个所有优惠

foreach ($this->headquarters()->where('headquarter', 'Leon')[0]['offers'] as $offer) {
            print_r($offer);
        }

或尝试此代码

    $offer = collect($this->headquarters()->where('headquarter', $headquarter)
                            ->first()['offers'])
                    ->where('slug', $slug)->first();

答案 1 :(得分:1)

你$ hq ['offers']是一个数组,你应该以$ hq ['offers'] [0] ['slug']的形式访问。

 $offer = $this->headquarters()
        ->filter(function($hq) use ($headquarter, $slug) {
            return $hq['headquarter'] == $headquarter && in_array($slug, array_column($hq['offers'], 'slug'));
        });