为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 该多维数组如何递归循环?

PHP 该多维数组如何递归循环?

PHP
动漫人物 2019-03-18 18:04:08
$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] ];
查看完整描述

2 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

<?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)
  }
}
查看完整回答
反对 回复 2019-03-18
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

    $data = new \RecursiveArrayIterator($data);
    $iterator = new \RecursiveIteratorIterator($data,\RecursiveIteratorIterator::SELF_FIRST);
    $iteratorArr = [];
    foreach ($iterator as $key=>$element) {
    }

试试RecursiveArrayIterator递归

查看完整回答
反对 回复 2019-03-18
  • 2 回答
  • 0 关注
  • 407 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信