Reputation:
I have this associative array, I want to get price
's lowest value from those arrays
array (size=3)
0 =>
array (size=21)
'quantity' => int 6
'product_id' => int 3
'category_id' => string '2' (length=1)
'price' => float 18.73
1 =>
array (size=21)
'quantity' => int 21
'product_id' => int 6
'category_id' => string '1' (length=1)
'price' => float 0.26
2=>
array (size=21)
'quantity' => int 34
'product_id' => int 6
'category_id' => string '1' (length=1)
'price' => float 0.63
I have tried
foreach ($products as $key_id => $prod) {
$lowest = $prod['price'];
if($prod['price'] < $lowest) {
// what to do here
}
}
I want to get product with lowest price and its product_id
too, something like
product_id => 6 , price => 0.26
Upvotes: 0
Views: 198
Reputation: 2161
In php >= 5.5
$min = min(array_column($products, 'price'));
In php >= 5.3(suggested by deceze)
$min = min(array_map(function (array $product) { return $product['price']; }, $products));
In php >= 5.0
$prices = array();
foreach ($products as $product) {
$prices[] = $product['price'];
}
$min = min($prices);
EDIT
To find both product_id and you could use this:
$min = PHP_INT_MAX;
$product_id = 0;
foreach ($products as $product) {
if ($product['price'] < $min) {
$product_id = $product['product_id'];
$min = $product['price'];
}
}
array column manual page
min manual page
array_map manual page
anonymous functions manual page
Upvotes: 3
Reputation: 522500
That's where a reduce operation is very appropriate:
$lowest = array_reduce($products, function ($lowest, array $product) {
return !$lowest || $product['price'] < $lowest ? $product['price'] : $lowest;
});
Upvotes: 2
Reputation: 33196
You should only set the lowest price if it is lower than the current lowest price.
// Set $low to the max value
$low = PHP_INT_MAX;
foreach ($products as $key_id => $prod) {
// If the price is lower than the current lowest, change the lowest price
if($prod['price'] < $lowest) {
$low = $prod['price'];
}
}
Upvotes: 0