根据条件从数组中获取最小/最大值

3
$array = [ [ 'Name' => 'Product 1', 'Quantity' => 0, 'Price' => 70  ], 
           [ 'Name' => 'Product 2', 'Quantity' => 2, 'Price' => 100 ],
           [ 'Name' => 'Product 3', 'Quantity' => 2, 'Price' => 120 ] ];

echo min( array_column( $array, 'Price' ) ); // 70

它确实可以获得min价格,但我还想检查数量,在这种情况下,100将是最低的。

是否有一种优雅的方法可以在不循环的情况下完成这个任务?


2
你是否正在尝试寻找数量大于0的最低价格? - Object Manipulator
@ObjectManipulator 是的,没错。 - eozzy
数组列是内存浪费。遍历数组。 - Peter Chaula
3个回答

3

用array_filter救火!

在检查最小值之前,先从数组中删除数量为0的元素。

echo min( array_column( array_filter($array,function($v) { 
return $v["Quantity"] > 0; }), 'Price' ) ); 

为了使它更易读
$filtered=array_filter($array,function($v) { return $v["Quantity"] > 0; });
echo min( array_column( $filtered, 'Price' ) );

Fiddle

还有一个老派版本,不包含所有闭包。

foreach($array as $v)
{
   if($v["Quantity"]>0 && (!$min || $v["Price"]<$min))
   $min=$v["Price"];
}

Fiddle


0

你需要使用 array_filter() 过滤掉数量为 0 的数组索引。

$filtered_array = array_filter($array, function($v) {
    return $v['Quantity'];
});

echo min( array_column( $filtered_array, 'Price' ) );

0
    $array = [[ 'Name' => 'Product 1', 'Quantity' => 0, 'Price' => 70], 
             ['Name' => 'Product 2', 'Quantity' => 2, 'Price' => 100],
             ['Name' => 'Product 3', 'Quantity' => 2, 'Price' => 120]];

    $price=array();

    for($i=0; $i<count($array);$i++){
      $price[$i]=$array[$i]['Price'];  
    }

    echo  min($price); //70

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接