如何为使用PHP递归函数返回数组? [英] How to return array for a recursive function using PHP?
问题描述
我有一个多维数组是这样的:
I have a Multi-dimensional array like this:
<pre>Array
(
[0] => Array
(
[id] => 52a83521-0914-4264-8fd9-07d9c601692a
[role_id] => 2
[children] => Array
(
[0] => Array
(
[id] => 54c1f5e4-b52c-4e17-b1bf-1f4616091b4e
[role_id] => 8
[children] => Array
(
[0] => Array
(
[id] => 54c20aba-201c-40ce-b3df-22d516091b4e
[role_id] => 9
)
[1] => Array
(
[id] => 54c20f4b-6e44-40ec-ae22-223a16091b4e
[role_id] => 9
)
)
)
[1] => Array
(
[id] => 54c1f8bb-ebac-466b-a83f-13a416091b4e
[role_id] => 8
)
)
)
)
</pre>
我需要填充此数组所有ROLE_ID秩序。我试着用递归函数是这样的:
I need to get populate all role_id from this array in order. I tried using recursive function like this:
<?php
public function tree_check($tree){
$tree_keys = $this->_recursion($tree);
print_r($tree_keys);
}
public function _recursion($tree){
foreach ($tree as $n => $v)
{
if(isset($v['role_id'])){
$key_arr[] = $v['role_id'];
}
if (is_array($v))
$this->_recursion($v);
}
return $key_arr;
}
我期待下面的输出中:
I am expecting the following ouput:
<pre>
Array(
[0]=>2,
[1]=>8,
[2]=>9,
[3]=>9,
[4]=>8
)
</pre>
在这里,我无法达到我的预期输出。阵列的水平可以动态变化,这就是为什么我与递归函数做了。
Here, I cannot achieve my expected output. The level of array may vary dynamically and that is why I have done it with recursive function.
我应该怎样从递归函数返回数组?
How should I return the array from recursive function?
一直以来,我不知道如何深度是我的数组,我怎么能找到最后的键值对数组的?
Since, I don't know how depth is my array, how can I find the last key value pair of array?
推荐答案
您可以使用通过元素的 RecursiveIteratorIterator :
You can go through the elements using a RecursiveIteratorIterator:
function listRolesRecursive($myArray) {
$res = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if($k === "role_id") {
$res[] = $v;
}
}
return $res;
}
$res = listRolesRecursive($arr);
var_dump($res);
它应该做的伎俩。
It should do the trick.
这篇关于如何为使用PHP递归函数返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!