我有这样一个数组:
array(2) {
[1] => array(3) {
[3] => array(3) {
["data"] => array(3) {
["id"] => string(1) "3"
["depth"] => string(1) "1"
["parent_id"] => NULL
}
}
[4] => array(3) {
["data"] => array(3) {
["id"] => string(1) "4"
["depth"] => string(1) "1"
["parent_id"] => NULL
}
}
[2] => array(3) {
["data"] => array(3) {
["id"] => string(1) "2"
["depth"] => string(1) "1"
["parent_id"] => NULL
}
}
}
[2] => &array(3) {
[15] => array(3) {
["data"] => array(3) {
["id"] => string(2) "15"
["depth"] => string(1) "2"
["parent_id"] => string(1) "3"
}
}
[16] => array(3) {
["data"] => array(3) {
["id"] => string(2) "16"
["depth"] => string(1) "2"
["parent_id"] => string(1) "2"
}
}
[18] => array(3) {
["data"] => array(3) {
["id"] => string(2) "18"
["depth"] => string(1) "2"
["parent_id"] => string(1) "4"
}
}
}
}
第一级表示深度(1没有子节点,2有父节点但没有子节点,等等)。数组项的顺序正确。我需要以相同的顺序获得不同的数组(当然依赖于级别)。
array(6) {
[3] => array(3) {
["data"] => array(3) {
["id"] => string(1) "3"
["depth"] => string(1) "1"
["parent_id"] => NULL
}
}
[15] => array(3) {
["data"] => array(3) {
["id"] => string(1) "15"
["depth"] => string(1) "1"
["parent_id"] => 3
}
}
[4] => array(3) {
["data"] => array(3) {
["id"] => string(1) "4"
["depth"] => string(1) "1"
["parent_id"] => NULL
}
}
[18] => &array(3) {
["data"] => array(3) {
["id"] => string(2) "18"
["depth"] => string(1) "2"
["parent_id"] => string(1) "4"
}
}
[2] => array(3) {
["data"] => array(3) {
["id"] => string(2) "2"
["depth"] => string(1) "2"
["parent_id"] => NULL
}
}
[16] => array(3) {
["data"] => array(3) {
["id"] => string(2) "16"
["depth"] => string(1) "2"
["parent_id"] => string(1) "2"
}
}
}
**
* *
我找到了解决方案,但我不知道如何从中进行递归。它只适用于两层。第三层是秩序不好。变量$this->hierarchicalData包含第一个数组。
$_sortedHierarchyData = array();
foreach ($this->hierarchicalData as $levelKey => $_level) {
foreach ($_level as $itemKey => $item) {
if (isset($this->hierarchicalData[$levelKey + 1])) {
$_sortedHierarchyData[$item['data']['id']] = $item;
$children = $this->searchChildrenFromLevelOfHieararchicalSortedData($item['data']['id'], $this->hierarchicalData[$levelKey + 1]);
$_sortedHierarchyData += $children;
}
}
}
function searchChildrenFromLevelOfHieararchicalSortedData($parent_id, $level)
{
$_children = array();
foreach ($level as $key => $item) {
if ($item['data']['parent_id'] === $parent_id) {
$_children[$key] = $item;
}
}
return $_children;
}