douzhuanfen5923 2019-05-01 07:06
浏览 43
已采纳

使用php [duplicate]从数组中获取Min和Max

This question already has an answer here:

I am facing an issue getting my desired value from an array, in PHP

Look at my array

 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")

 );

I need Min Price and Max Discount, this time, I need array ID 2, that is

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

Because in this array price is lower 2, and discount is 4, on next record you can see discount is much higher that is 5, but price is 3 which is higher then 2, so Desired result is sub array id 2

Kindly let me know How can i do this ?

</div>
  • 写回答

1条回答 默认 最新

  • duanmu6231 2019-05-01 07:29
    关注

    Please try to use this solution

    $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
    

    Algorithm description:

    • Find the minimum price in all array
    • Loop through all minimum price elements and find the maximum discount value
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?