如何从Laravel中的数组获取值

时间:2019-01-29 09:39:15

标签: php arrays laravel

我有一个3级类别。我需要获得3级类别的业务。

我写这段代码:

$main_cat = Category::where(['slug' => $url])->first();
$lev_cat2 = Category::where(['parent_id' => $main_cat->id, 'status' => '1'])->get();
 foreach ($lev_cat2 as $subCategory) {
            $cat_ids_lv2[] = $subCategory->id . ',';
        }
 foreach ($lev_cat2 as $subCat) {
            $lev_cat3[] = Category::where(['parent_id' => $subCat->id, 'status' => '1'])->pluck('id')->toArray();
        }

dd($lev_cat3);

然后我得到了正确的数组:

array:5 [▼
  0 => array:3 [▼
    0 => 145
    1 => 146
    2 => 147
  ]
  1 => array:3 [▼
    0 => 148
    1 => 149
    2 => 150
  ]
  2 => array:3 [▼
    0 => 151
    1 => 152
    2 => 153
  ]
  3 => array:3 [▼
    0 => 154
    1 => 155
    2 => 156
  ]
  4 => []
]

现在我不知道如何获取145,146,147,148,149,...这样的值来将主题传递给

Business::where(['category_id'=> [145,146,147,148,...]]->get();

当然是动态的。

2 个答案:

答案 0 :(得分:2)

您可以使用laravel收集助手:

Business::whereIn('category_id', collect($lev_cat3)->flatten()->all())->get();

答案 1 :(得分:0)

自PHP 5.5.0起,就有一个内置函数array_column正是这样做的。

您可以使用它将数组的php数组转换为单个数组,然后像这样使用它

$category_ids = array_column($lev_cat3);

Business::where(['category_id'=> $category_ids]]->get();