0

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 ?

dewshare
  • 45
  • 8
  • 1
    If you sort the array by the price ascending and the discount descending, then the resultant array will be in the order your after( i.e. `array_multisort(array_column($data, "price"), SORT_ASC, array_column($data, "discount"), SORT_DESC, $data );`). Then use element `[0]` of that array for the item your after. – Nigel Ren May 01 '19 at 07:35
  • Also if this is the result of a SQL query - you can add an ORDER BY clause similar to the sort above which should give you the same result (but without the SQL it's difficult to know) – Nigel Ren May 01 '19 at 07:38

1 Answers1

0

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
alexey-novikov
  • 593
  • 2
  • 16