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.
除非我失去了一些东西,遍历数组寻找的东西的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;
}
递归版本,不包括子元素
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;
}
它需要递归作为数组可以更深 – 2011-12-28 13:49:57
它的工作只有顶级的元素,不适合儿童。 – cnkt 2011-12-28 13:50:11
@Topener:问题在答案中改变了,所以我正在修复以适应。 - cnkt:在这工作,给我一分钟左右。 – 2011-12-28 13:51:38