也許是矯枉過正,但它很有趣,使用RecursiveIterators :)
UPDATE:也許對舊版本的PHP來說過分了,但是大於5.6(特別是7.0),我完全可以毫無疑問地使用它。
function recursiveFind(array $haystack, $needle)
{
$iterator = new RecursiveArrayIterator($haystack);
$recursive = new RecursiveIteratorIterator(
$iterator,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($recursive as $key => $value) {
if ($key === $needle) {
return $value;
}
}
}
UPDATE:此外,作爲PHP 5.6,搭配發電機就可以輕鬆遍歷其通過過濾器,不僅是第一個所有要素:
function recursiveFind(array $haystack, $needle)
{
$iterator = new RecursiveArrayIterator($haystack);
$recursive = new RecursiveIteratorIterator(
$iterator,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($recursive as $key => $value) {
if ($key === $needle) {
yield $value;
}
}
}
// Usage
foreach (recursiveFind($haystack, $needle) as $value) {
// Use `$value` here
}
你怎麼會不知道它在什麼級別? – 2010-10-20 07:27:03