cnk*_*nkt 5 php arrays recursion iterator multidimensional-array
我有这样的数组:
array(
array(
'id' => 1,
'children' => array(
array(
'id' => 2,
'parent_id' => 1
),
array(
'id' => 3,
'parent_id' => 1,
'children' => array(
array(
'id' => 4,
'parent_id' => 3
)
)
)
)
)
);
Run Code Online (Sandbox Code Playgroud)
如果有必要,阵列会更深入.我需要为任何给定的id获取孩子.
谢谢.
function getChildrenOf($ary, $id)
{
foreach ($ary as $el)
{
if ($el['id'] == $id)
return $el;
}
return FALSE; // use false to flag no result.
}
$children = getChildrenOf($myArray, 1); // $myArray is the array you provided.
Run Code Online (Sandbox Code Playgroud)
除非我遗漏了某些东西,否则迭代数组寻找与id你正在寻找的密钥和id 匹配的东西(然后返回它作为结果).您也可以迭代搜索(并给我一秒钟发布代码,这将检查parentId密钥)...
-
递归版,包括子元素:
function getChildrenFor($ary, $id)
{
$results = array();
foreach ($ary as $el)
{
if ($el['parent_id'] == $id)
{
$results[] = $el;
}
if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE)
{
$results = array_merge($results, $children);
}
}
return count($results) > 0 ? $results : FALSE;
}
Run Code Online (Sandbox Code Playgroud)
递归版,不包括子元素
function getChildrenFor($ary, $id)
{
$results = array();
foreach ($ary as $el)
{
if ($el['parent_id'] == $id)
{
$copy = $el;
unset($copy['children']); // remove child elements
$results[] = $copy;
}
if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE)
{
$results = array_merge($results, $children);
}
}
return count($results) > 0 ? $results : FALSE;
}
Run Code Online (Sandbox Code Playgroud)