PHP 多维数组中,如何获取指定键名同级前一个数组的内容?
问题:
给定一个多维数组,如何通过一个函数根据一个“键名”获取到同级的前一个数组的内容?
例如,给定以下数组:
$all = []; $a = ["horse" => "0", "dog" => "1", "cat" => "2"]; $b = ["horse" => "a", "dog" => "b", "cat" => "c"]; $c = ["horse" => "a1", "dog" => "b2", "cat" => "c3"]; $all["123456"]["511"] = $a; $all["123456"]["523"] = $b; $all["123456"]["607"] = $c; var_dump($all);
如何通过键名“523”获取到键名“511”的内容?
解答:
我们可以使用以下函数获取同级前一个数组的内容:
function getpreviousarray($all, $key) { $keys = array_keys($all); $index = array_search($key, $keys); if ($index > 0) { return $all[$keys[$index - 1]]; } return null; }
使用方式:
$previousarray = getpreviousarray($all, "523"); var_dump($previousarray);
输出结果:
array(3) { ["Horse"] => string(1) "0" ["Dog"] => string(1) "1" ["Cat"] => string(1) "2" }