php 在二维数组中查找一列具有特定值而另一列具有最小值的行

euoag5mw  于 2023-04-04  发布在  PHP
关注(0)|答案(3)|浏览(139)

我有下面的2D数组,我想得到[0]列中最小值的键,如果done等于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",
    ),
);
nlejzf6q

nlejzf6q1#

试试这个

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

bsxbgnwa2#

给你。

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

echo $array_keys[$key];
ibps3vxo

ibps3vxo3#

您应该在一次遍历数组中执行所有检查。
我的代码片段将提供第一个限定行的键(包含最低的[0]值,并且done值为no)。
代码:(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';

输出:

CityB

相关问题