試試這個:
/**
* @param $path array containing path
* @param $array search array
* @return element matching path or null
*/
function arr_search($path, &$array){
$tmp = &$array;
for($i = 0; $i < count($path); $i++){
if(!isset($tmp[$path[$i]])) return null;
$tmp = &$tmp[$path[$i]];
}
return $tmp;
}
$arr = array(
'a' => array(
'b' => array(
'c' => 'abc',
),
'd' => array('ad'),
),
10 => array(100, 200, 300),
);
var_dump(arr_search(array('a', 'b', 'c'), $arr));
var_dump(arr_search(array('a', 'd'), $arr));
var_dump(arr_search(array(10, 100), $arr));
var_dump(arr_search(array(10, 1), $arr));
//編輯前面的例子是錯誤的,所以這裏是新的:)
function arr_search($key, $array){
$values = array();
if(array_key_exists($key, $array)) $values[] = $array[$key];
$stack = array_values($array);
while($tmp = array_pop($stack)){
if(is_array($tmp)){
foreach($tmp as &$v){
array_push($stack, $v);
}
if(array_key_exists($key, $tmp)){
$values[] = $tmp[$key];
}
}
}
return $values;
}
$arr = array(
'a' => array(
'b' => array(
'c' => 'abc',
),
'd' => array('ad'),
),
'e' => array(
'a' => array(
'b' => 'abc',
),
'b' => array('xyz'),
),
10 => array(100, 200, 300),
);
var_dump(arr_search('b', $arr));
var_dump(arr_search(0, $arr));
如何是你要求的不同於$ arr [「some_inner_array」] [「another_array_possible」] [「key」]'? – Jon 2011-12-19 13:58:08
到目前爲止你的代碼是什麼? – SERPRO 2011-12-19 14:03:43
我不知道密鑰是否在這裏arr [「some_inner_array」] [「another_array_possible」] [key「]。也許是這裏:arr [」completely_different_array「] [key」] – 2011-12-19 14:04:52