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