简体   繁体   中英

Php find key for min value in 2D array

I have the following 2D array and I would like to get the key of the smalest value in the [0] column if done is equal to no

$graph= array(
"CityA" => array(
    "0" => "1",
    "1" => "CityC",
    "done" => "no",
    ),
"CityB" => array(
    "0" => "4",
    "1" => "CityA",
    "done" => "no",
    ),
"CityC" => array(
    "0" => "5",
    "1" => "CityA",
    "done" => "no",
    ),
);

Try this,

$arr = array_map(function($v){return $v[0];}, $graph);
$key = array_keys($arr, min($arr));

Here you go.

$tes = min( array_column( $graph, 0 ) );
$key = array_search( $tes, array_column( $graph, 0 ) );
$array_keys = array_keys($graph);

echo $array_keys[$key];

You should perform all of your checks in a single pass through your array.

My snippet will provide the first qualifying (contains the lowest [0] value AND has a done value of no ) row's key.

Code: ( Demo )

$graph = [
    "CityB" => ["0" => "1", "1" => "CityA", "done" => "no"],
    "CityA" => ["0" => "1", "1" => "CityC", "done" => "no"],
    "CityD" => ["0" => "1", "1" => "CityD", "done" => "yes"],
    "CityC" => ["0" => "5", "1" => "CityA", "done" => "no"]
];

$result = [];
foreach ($graph as $key => $row) {
    if ($row['done'] === 'no' && (!isset($result[$key]) || $row[0] < $result[$key])) {
        $result[$key] = $row[0];
    }
}

echo key($result) ?? 'No "done => no" rows';

Output:

CityB

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