可以使用遞歸函數像這樣:
<?php
function getSetValues($array, $searchKeys) {
$values = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$values = array_merge($values, getSetValues($value, $searchKeys));
} else if (in_array($key, $searchKeys)) {
$values[] = $value;
}
}
return $values;
}
$values = getSetValues(array(
'foo' => array(
'bar' => 123,
'rab' => array(
'oof' => 'abc'
),
'oof' => 'cba'
),
'oof' => 912
), array('bar', 'oof')); //Search for keys called 'bar' or 'oof'
print_r($values);
?>
將輸出:
Array
(
[0] => 123 (because the key is 'bar')
[1] => abc (because the key is 'oof')
[2] => cba (because the key is 'oof')
[3] => 912 (because the key is 'oof')
)
DEMO
'遞歸'是您的關鍵字。 (但是你也可以用包含當前數組的變量來循環) – ComFreek
你應該看看['array_walk_recursive'](http://php.net/manual/en/function.array-walk-recursive.php )功能。 – toro2k