dtkjthe4025
dtkjthe4025
2019-01-29 09:39
采纳率: 0%
浏览 1.1k
已采纳

如何从Laravel中的数组中获取值

I have a 3 level category. I need to gain businesses on level 3 category.

I write this code:

$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);

Then I got this array which is correct:

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 => []
]

now I dont know how can I get values like 145,146,147,148,149,... to pass theme to

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

of course dynamic.

图片转代码服务由CSDN问答提供 功能建议

我有一个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 => 数组:3 [▼
 0 =>  145 
 1 =>  146 
 2 =>  147 
] 
 1 => 数组:3 [▼
 0 =>  148 
 1 =>  149 
 2 =>  150 
] 
 2 => 数组:3 [▼
 0 =>  151 
 1 =>  152 
 2 =>  153 
] 
 3 => 数组:3 [▼
 0 =>  154 
 1 =>  155 
 2 =>  156 
] 
 4 =>  [] 
] 
   
 
 

现在我不知道如何获得像145,146,147,148,149,...这样的值来将主题传递给 Business :: where(['category_id'=> [145,146,147,148,...]] - > get();

of 当然是动态的。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanfu1942
    duanfu1942 2019-01-29 09:50
    已采纳

    You can use laravel collection helpers :

    Business::whereIn('category_id', collect($lev_cat3)->flatten()->all())->get();
    
    点赞 评论
  • dousi2553
    dousi2553 2019-01-29 10:58

    Since PHP 5.5.0 there is a built-in function array_column which does exactly this.

    You can use it to Converting php array of arrays into single array then use it like this

    $category_ids = array_column($lev_cat3);
    
    Business::where(['category_id'=> $category_ids]]->get();
    
    点赞 评论

相关推荐