我有数组结构,我必须得到叶子。 例 第一种类型的数组
[name] => long_desc
[values] => Array
(
[0] => Array
(
[values] => xxx
)
)
)
或
(
[name] => long_desc
[values] => Array
(
[0] => Array
(
[name] => span
[values] => Array
(
[0] => Array
(
[values] => xxx
)
)
)
如何获得价值xxx的名称?我的阵列有更长的深度,使用foreach多次不能正常工作。我试过recursivearrayiterator但没有帮助。
答案 0 :(得分:0)
function testArrayItem($item, $key)
{
if ( $item == "xxx" ) {
echo "Found xxx on key {$key}";
}
}
array_walk_recursive($array, 'testArrayItem');
编辑: 如果你想得到整个分支,它通向叶子,你可以递归迭代它:
function getPathToLeafRecursive(array $input, array &$branch)
{
foreach ( $input as $key => $item ) {
if ( 'xxx' == $item ) {
$branch[] = $key;
return true;
}
if ( is_array($item) ) {
$res = getPathToLeafRecursive($item, $branch);
if ( $res ) {
$branch[] = $key;
return true;
}
}
}
return false;
}
$found_branch = array();
getPathToLeafRecursive($array, $found_branch);
$found_branch = array_reverse($found_branch);
var_export($found_branch);
答案 1 :(得分:0)
以下是如何查找叶节点,而不依赖于密钥的名称。它相当原始,可以使用一些OOP,但它演示了基本的算法:
$array = array(
array('name' => 'span',
'values' => array('values' => 'xxx', array('values' => 'yyy')),
'stuff' => '123'
)
);
$deepest_depth = 0;
$deepest_node = null;
find_leaf($array, 0);
function find_leaf($array, $current_depth) {
global $deepest_depth, $deepest_node;
do {
$current_node = current($array);
if (is_array($current_node)) {
find_leaf($current_node, $current_depth+1);
} else {
if ($deepest_node === null || $current_depth > $deepest_depth) {
$deepest_depth = $current_depth;
$deepest_node = $current_node;
}
}
next($array);
} while ($current_node !== FALSE);
}
echo $deepest_node;
答案 2 :(得分:0)
这个xxx值是多少?你知道内容吗?你只是想知道它在数组中?
在这种情况下,您可以将RecursiveArrayIterator与RecursiveFilterIterator一起使用。
如果你想得到叶子的所有“值”键,那么你也可以使用RecursiveFilterIterator,但是例如检查标量的“值”。