[英]Get min/max value from array based on condition
$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
将是最低的。
有没有循环的优雅方式来做到这一点?
array_filter来救援!
在检查min之前,从数组中删除Quantity设置为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' ) );
还有一个没有所有封闭的旧式版本
foreach($array as $v)
{
if($v["Quantity"]>0 && (!$min || $v["Price"]<$min))
$min=$v["Price"];
}
您需要使用array_filter()过滤掉数量为0的数组索引。
$filtered_array = array_filter($array, function($v) {
return $v['Quantity'];
});
echo min( array_column( $filtered_array, 'Price' ) );
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.