PHP 该多维数组如何递归循环?
本文介绍了PHP 该多维数组如何递归循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
$arr = [
[
'id' => 1,
'children' => [
'id' => 2,
'children' => [
'id' => 3,
'children' => [
'id' => 4
]
]
]
],
[
'id' => 5,
'children' => [
'id' => 6,
]
],
[
'id' => 7
]
];
存在children数组则将children数组里的id赋值给新的数组,最终组成新的数组如下:
$arr2 = [
[1,2,3,4],
[5,6],
[7]
];
解决方案
<?php
$arr = [
[
'id' => 1,
'children' => [
'id' => 2,
'children' => [
'id' => 3,
'children' => [
'id' => 4
]
]
]
],
[
'id' => 5,
'children' => [
'id' => 6,
]
],
[
'id' => 7
]
];
function pushChild($children, &$container)
{
$container[] = $children['id'];
if (! isset($children['children'])) {
return;
}
pushChild($children['children'], $container);
}
$arr2 = [];
foreach ($arr as $item) {
$result = [];
pushChild($item, $result);
$arr2[] = $result;
}
var_dump($arr2);
输出
~ ❯❯❯ php test.php
array(3) {
[0]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
[1]=>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}
[2]=>
array(1) {
[0]=>
int(7)
}
}
这篇关于PHP 该多维数组如何递归循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文