基于元素值的Laravel过滤器数组

I have the following array that I need to filter it and get just the elements which have type = 1

array:5 [
  0 => array:3 [
    "id" => 1
    "name" => "Agua Corriente"
    "type" => 1
  ]
  1 => array:3 [
    "id" => 2
    "name" => "Cloaca"
    "type" => 1
  ]
  2 => array:3 [
    "id" => 3
    "name" => "Gas Natural"
    "type" => 2
  ]
  3 => array:3 [
    "id" => 4
    "name" => "Internet"
    "type" => 3
  ]
  4 => array:3 [
    "id" => 5
    "name" => "Electricidad"
    "type" => 3
  ]
]

这是预期的结果:

array:2 [
  0 => array:3 [
    "id" => 1
    "name" => "Agua Corriente"
    "type" => 1
  ]
  1 => array:3 [
    "id" => 2
    "name" => "Cloaca"
    "type" => 1
  ]
]

I'm trying to solve it with Arr::where helper but I'm not getting the expected result. Does anyone can help me?

问候

评论
  • qnobis
    qnobis 回复
    $filteredArray = Arr::where($myArray, function ($value, $key) {
        return $value['type'] == 1;
    });
    

    This is how you can use Arr::where in your array, and should work fine.

    同样,对于类似laravel集合这样的东西,它们确实具有方便的工具,您也应该看看它。

    如果要基于动态分配的变量进行过滤,大多数情况下可以将其简单地注入嵌套函数中,例如:

        $type = 1;
        $filteredArray = Arr::where($myArray, function ($value, $key) use($type) {
            return $value['type'] == $type;
        });
    
  • id_aut
    id_aut 回复

    You can use collection where:

    collect($array)->where('type', 1)->all();