Supposing I have this array in PHP:
Array
(
[0] => Array
(
[color] => Yellow
[name] => Banana
[quantity] => 124
)
[1] => Array
(
[color] => Red
[name] => Cherry
[quantity] => 24
)
[2] => Array
(
[color] => Yellow
[name] => Apple
[quantity] => 224
)
)
How can I reduce this array if :
color
is yellow andquantity
is the lowest
So from the example above, I should have only this array:
Array
(
[0] => Array
(
[color] => Yellow
[name] => Banana
[quantity] => 124
)
)
What I have tried so far:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['quantity']);
}, PHP_INT_MAX);
Thanks for any help.
3
Answers
I would just use a simple loop like this, because it’s readable and easy to understand what is happening.
Output
If you want
$min
to still be an array like your example output, you can just add it to an array like this.Output
A possible solution.
This solution takes into consideration what has already been created by the applicant, completing the code to obtain the required result.
The first array_filter selects all rows that have color = ‘Yellow’, decreasing the dataset to process.
With array_reduce we find the smallest value of quantity, like @F_M did, but on a smaller dataset.
Finally with another array_filter we are going to extract the row with the value just found.
I tried to make a more versatile, generic function that could be modified to suit other similar scenarios where the input array does not necessarily contain the keys/values cited in the question.
The above yields:
If the criteria change and you need the highest rather than lowest that can be quickly realised by modifying the
$dir
variable.