Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter on collection with multidimensional array

I have a collection that is a multidimensional array. I need to filter only items with a specific color, however the color field is within a multidimensional. Normally it is as easy as $collection->where('color','green').

How would I do this WHERE clause on something more complex?

[
    'product' => 'Desk', 
    'info' => [
            'namespace' => 'green', 
            'key' => 'blue',
        ],
        [
            'namespace' => 'orange', 
            'key' => 'red',
        ],
    ]
],
[
    'product' => 'Chair', 
    'info' => [
            'namespace' => 'green', 
            'key' => 'blue',
        ],
        [
            'namespace' => 'purple', 
            'key' => 'pink',
        ],
    ]
],

In this array how would I get all products that has the value green for the key info['namespace']?

$collection->where('info['namespace']','green') is basically what I am looking for.

like image 946
Cory Fail Avatar asked Oct 22 '25 21:10

Cory Fail


1 Answers

I think you will have better results with the filter collection method (where doesn't seem to do nested very gracefully).

Laravel Documentation on the filter method

Example:

$greenNamespaceCollection = $collection->filter(function ($value, $key) {

    return collect($value['info'])->contains('namespace' 'green');
})
like image 63
matpb Avatar answered Oct 25 '25 13:10

matpb