我有这个关联数组,我想从这些数组中得到price
的最低值
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
我试过了
foreach ($products as $key_id => $prod) {
$lowest = $prod['price'];
if($prod['price'] < $lowest) {
// what to do here
}
}
我想获得价格最低的产品及其product_id
,例如
product_id => 6 , price => 0.26
答案 0 :(得分:3)
在php&gt; = 5.5
$min = min(array_column($products, 'price'));
在php&gt; = 5.3(由deceze建议)
$min = min(array_map(function (array $product) { return $product['price']; }, $products));
在php&gt; = 5.0
中$prices = array();
foreach ($products as $product) {
$prices[] = $product['price'];
}
$min = min($prices);
修改强>
要查找product_id,您可以使用:
$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
答案 1 :(得分:2)
这是减少操作非常合适的地方:
$lowest = array_reduce($products, function ($lowest, array $product) {
return !$lowest || $product['price'] < $lowest ? $product['price'] : $lowest;
});
答案 2 :(得分:0)
如果价格低于当前最低价格,则只应设置最低价格。
// 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'];
}
}