我有一个像这样的数组
Array
(
[0] => Array
(
[id] => 1 [children] => Array
(
[0] => Array
(
[id] => 2 [children] => Array
(
[0] => Array
(
[id] => 3 [children] => Array
(
[0] => Array
(
[id] => 4
)
)
)
)
)
)
)
[1] => Array (
[id] => 5
)
[2] => Array
(
[id] => 6
)
[3] => Array
(
[id] => 7
)
[4] => Array
(
[id] => 8
)
[5] => Array
(
[id] => 9
)
)
这是动态生成的数组,我需要一个函数以该数组作为输入并返回每个ID及其父ID
根据此数组,id 2是id 1的孩子,id 3是id 3的孩子,而id 4是id 3的孩子
最终结果ID 1是ID 2的父级,ID 2是ID 3的父级,ID 3是ID 4的父级,ID 5-9没有父级,因此它们的默认值为0
答案 0 :(得分:0)
除了您自己没有付出任何努力外,我还是会发布解决方案,以防有人不知道使用PHP的RecursiveIteratorIterator
样本数据:
$arrData = [
[
'id' => 1,
'children' => [
'id' => 2,
'children' => [
'id' => 3,
'children' => [
'id' => 4
]
]
]
],
[
'id' => 5
],
[
'id' => 6
],
[
'id' => 7
],
[
'id' => 8
],
[
'id' => 9
],
];
使用PHP内置的int迭代器类
$arrDataConverted = [];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arrData));
foreach($iterator AS $key => $value)
{
$arrParentdata = $iterator->getSubIterator($iterator->getDepth()-1);
$arrItem = [
'id' => $value,
'parent' => (isset($arrParentdata['id'])) ? $arrParentdata['id'] : 0
];
$arrDataConverted[] = $arrItem;
}
print_r($arrDataConverted);