【发布时间】:2017-12-15 04:19:59
【问题描述】:
我有一个这样的数组:
$navArray = array(
array(
'id'=>1,
'text'=>'1A',
'href'=>'1a',
'childs'=>array(
array(
'id'=>2,
'text'=>'1B',
'href'=>'1b',
'childs'=>array(
array(
'id'=>4,
'text'=>'4D',
'href'=>'4d',
'childs'=>array()
),
array(
'id'=>5,
'text'=>'5E',
'href'=>'5e',
'childs'=>array(
array(
'id'=>6,
'text'=>'6F',
'href'=>'6f',
'childs'=>array()
),
array(
'id'=>7,
'text'=>'7G',
'href'=>'7g',
'childs'=>array()
),
)
),
)
),
array(
'id'=>3,
'text'=>'3C',
'href'=>'3c',
'childs'=>array(
array(
'id'=>8,
'text'=>'8H',
'href'=>'8h',
'childs'=>array()
)
)
)
)
)
);
我可以遍历多维数组并返回'key' => 'value'对:
displayRecs($navArray);
function displayRecs($navArray) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($navArray));
foreach($iterator as $key => $value) {
echo ($key . ' ' . $value . '<br>');
}
}
下面的快照可视化了结果。
我想最终得到以下数组:
$finalArray = array(
array('id'=>1,'parent'=>0,'text'=>'1A','href'=>'1a'),
array('id'=>2,'parent'=>1,'text'=>'2B','href'=>'2b'),
array('id'=>3,'parent'=>1,'text'=>'3C','href'=>'3c'),
array('id'=>4,'parent'=>2,'text'=>'4D','href'=>'4d'),
array('id'=>5,'parent'=>2,'text'=>'5E','href'=>'5e'),
array('id'=>6,'parent'=>5,'text'=>'6F','href'=>'6f'),
array('id'=>7,'parent'=>5,'text'=>'7G','href'=>'7g'),
array('id'=>8,'parent'=>3,'text'=>'8H','href'=>'8h'),
);
如何获取父数组的“id”?
【问题讨论】:
标签: php arrays sorting recursion parent-child