Zoric
Zoric

Reputation: 61

get cheap price with min() from array

Im using min() to get the cheapest price out of an array but its showing the expensive one instead of the cheap one. i also need to get all the data from the cheap price array.

code

 $dumpData = array();

  if ( !empty($dumpData) && is_array($dumpData) ) {

    $minPriceArray = min($dumpData['data']);

    $price = $func->convert_amount($minPriceArray['currency'],   get_currency(), $minPriceArray['price']);
    echo '<span class="price"><small>From</small> '.$price.' '.get_currency().'</span>';

  }else{
    echo '<span class="price">No data found</span>';
  }

array

 array(4) {
   [0]=>
   array(8) {
     ["logo"]=>
     ["price"]=>
     int(649)
     ["currency"]=>
     string(3) ""
     ["availability"]=>
     string(7) "instock"
   },
   [1]=>
   array(8) {
     ["logo"]=>
     ["price"]=>
     int(849)
     ["currency"]=>
     string(3) ""
     ["availability"]=>
     string(7) "instock"
   },
   [2]=>
   array(8) {
   ...
   },
   [3]=>
   array(8) {
   ...
   }

 }

Upvotes: 0

Views: 2002

Answers (1)

Wolverine
Wolverine

Reputation: 1702

function find_min_price_array($arr) {
    $prices = array_column($arr, 'price');
    $min_price = min($prices);

    $min_price_array = array();

    foreach($arr as $key => $value) {
        if($value['price'] == $min_price) {
            $min_price_array[] = $value;
        }
    }

    return $min_price_array;
}

var_dump(find_min_price_array($arr));

The user-defined function find_min_price_array returns the array which contains the minimum price. It also returns the arrays which contain same minimum price.

array_column returns all the values of a column in the multi-dimensional array. array_column($arr, 'price') gets you all the prices in the arrays and then you can find the minimum value easily with min function. Then, you can check the minimum price against the price of each array in the multi-dimensional array in the loop.

Hope it helps!

Upvotes: 1

Related Questions