我有以下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",
),
);
答案 0 :(得分:4)
试试这个,
$arr = array_map(function($v){return $v[0];}, $graph);
$key = array_keys($arr, min($arr));
答案 1 :(得分:1)
你走了。
$tes = min( array_column( $graph, 0 ) );
$key = array_search( $tes, array_column( $graph, 0 ) );
$array_keys = array_keys($graph);
echo $array_keys[$key];
答案 2 :(得分:0)
输入:
$graph=[
"CityB"=>["0"=>"4","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"]
];
方法:
// remove all subarrays where 'done' != 'no'
$graph=array_filter($graph,function($a){return $a['done']=='no';});
// sort array on first column in subarray ASC while preserving keys
asort($graph);
// get first key
echo key($graph);
输出:
CityA
我认为这比克里斯的方式简单。