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.
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');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With