两级字符串索引关联数组的最小值


Lowest value of two level String indexed Associative Array

我有一个关联数组,我想从这些数组中得到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

In php>= 5.5

$min = min(array_column($products, 'price')); 

In php>= 5.3(由dec建议)

$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);

编辑

找到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_map手册页
匿名函数手册页

这就是reduce操作非常合适的地方:

$lowest = array_reduce($products, function ($lowest, array $product) {
    return !$lowest || $product['price'] < $lowest ? $product['price'] : $lowest;
});

您应该只在低于当前最低价时设置最低价。

// 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'];
    }
}