使用php从数组获取最小和最大

时间:2019-05-01 07:06:48

标签: php sql arrays

我在使用PHP从数组获取所需的值时遇到了问题

看看我的阵列

 array(

  "0"=>array("id"=>"255","price"=>"2","discount"=>"1"),
  "1"=>array("id"=>"256","price"=>"2","discount"=>"3"),
  "2"=>array("id"=>"257","price"=>"2","discount"=>"4"),
  "3"=>array("id"=>"255","price"=>"3","discount"=>"5")

 );

我需要最低价格和最高折扣,这一次,我需要阵列ID 2,即

"2"=>array("id"=>"257","price"=>"2","discount"=>"4"),

因为此数组中的价格低2,而折扣为4,在下一条记录中,您可以看到折扣高得多,为5,但价格为3,高于2,因此所需结果为子数组id 2 < / p>

请让我知道我该怎么做?

1 个答案:

答案 0 :(得分:0)

请尝试使用此解决方案

$array = array(
    "0" => array("id" => "255", "price" => "2", "discount" => "1"),
    "1" => array("id" => "256", "price" => "2", "discount" => "2"),
    "2" => array("id" => "257", "price" => "2", "discount" => "4"),
    "3" => array("id" => "255", "price" => "3", "discount" => "5"),
);

$minPrice = min(array_column($array, 'price'));
$maxDiscountIndex = $maxDiscount = 0;

foreach ($array as $key => $value) {
    if ($value['price'] == $minPrice && $maxDiscount < (int) $value['discount']) {
        $maxDiscountIndex = $key;
        $maxDiscount = $value['discount'];
    }
}

echo $maxDiscountIndex; // 2

算法说明:

  • 找到所有阵列的最低价格
  • 浏览所有最低价格要素并找到最大折扣值