简体   繁体   中英

find minimum value in multidimensional associative array

This is my array:

Array
(
    [0] => Array
        (
            [price] => 106.060500
            [unit] => 2.5900
        )

    [1] => Array
        (
            [price] => 108.981500
            [unit] => 2.1100
        )
)

What I am trying to find is the lowest [price] value. To then return both the [price] and [unit] values for later calculation.

So the returned value for this array would be:

Array (
 [price] => 106.060500
 [unit] => 2.5900
)

One only way I can think of is:

$i = array();
foreach ($pricearray as $array) {
    array_push($i, $array->price);
}
$minPrice = min($i);
foreach ($pricearray as $array) {
    if ($array->price == $minPrice) {
        $i= $array;
    }
}

I feel there must be an easier way, or at least a bit more elegant.

Try this:

<?php
foreach ($pricearray as $array){
    if (!isset($minarr)) $minarr = $array; 
    elseif ($array['price'] < $minarr['price']) $minarr = $array; 
}

Output $minarr:

Array
(
    [price] => 106.0605
    [unit] => 2.59
)
$minPrice = min(array_column($pricearray, 'price'));
$i = array_filter($pricearray, 
        function($i) use ($minPrice) { return $minPrice === $i['price']; });

or

usort($pricearray, function($i1,$i2) { return $i1['price'] - $i21['price']; });
$i = array_shift($pricearray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM