Php 如何按顺序从多维数组中获取数组
我有这种数组:Php 如何按顺序从多维数组中获取数组,php,arrays,recursion,multidimensional-array,Php,Arrays,Recursion,Multidimensional Array,我有这种数组: 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
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有没有子级的父级,等等)。数组项的顺序正确。我需要以相同的顺序获得不同的数组(当然,这取决于级别)
**
第一种解决方案
**
我找到了解决方案,但我不知道如何从中进行递归。它只适用于两个级别。第三个层次是秩序混乱。变量$this->hierarchycaldata包含第一个数组
$_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;
}
你试过了,什么?我什么都试过了,但我没能得到。我认为这将是需要使用一些递归,但我不知道如何。你能给我个建议吗?我用和第二个相同的数组做了第一个数组。第一个数组只是因为多维排序(alphabethical,但通过任意参数(为了简单起见,缺少这些参数))。但是只按不同的顺序返回原始数组要复杂得多。是否要数组[1]和数组[2]的组合?尝试了数组_合并?“+”可能也可以
$_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;
}