PHP取消嵌套多维数组中的所有元素

时间:2019-09-17 01:39:04

标签: php arrays

我在PHP中有一个多维数组,我想取消嵌套所有元素以将它们带到顶层。这是数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [color] => red

        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [color] => blue
                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [color] => green
                        )

                )

            [2] => Array
                (
                    [id] => 4
                    [color] => blue
                )

        )

    [2] => Array
        (
            [id] => 5
            [color] => purple
        )

)

我想要结束的是这个...所以基本上,它循环遍历数组,并取消嵌套它的任何组。抱歉,我不知道正确的术语。是否有PHP函数呢?我已经在堆栈上尝试了几种解决方案,但是它将所有键值对移动到顶部,而不仅仅是数组组,这只会造成混乱。

(
    [0] => Array
        (
            [id] => 1
            [id] => red                
        )
    [1] => Array
        (
            [id] => 2
            [color] => blue
        )

    [2] => Array
        (
            [id] => 3
            [color] => green
        )

    [3] => Array
        (
            [id] => 4
            [color] => blue
        )


    [4] => Array
        (
            [id] => 5
            [color] => purple
        )

)

谢谢!

3 个答案:

答案 0 :(得分:0)

您可以这样操作,选中Demo

$result = [];
array_walk_recursive($array,function(&$v)use($result){
   $result[] = $v;
});
$result = array_chunk($result,2);
$result = array_map(function($v){return array("id"=>$v[0],"color"=>$v[1]);});
print_r($result);

答案 1 :(得分:0)

您可以使用array_walk_recursive

打开包装
$i = 0;
array_walk_recursive($a, function($v,$k)use(&$r,&$i){
  $r[$i][$k] = $v;
  ($k == 'color') ? $i++ :$i; 
});
print_r($r);

工作示例:-https://3v4l.org/YPT2M

答案 2 :(得分:0)

使用以下简单的通用递归(无id,无颜色)

function flattenArray($arr = [])
{
    $retArr = [];
    foreach ($arr as $val) {
        if (is_array($val)) {
            $retArr[] = array_filter($val, function ($v) {
                return !is_array($v);
            });
            $retArr = array_merge(array_filter($retArr), flattenArray($val));
        }
    }
    return $retArr;
}
$arr = flattenArray($arr);

Demo

输出:-

Array
(
    [0] => Array
        (
            [id] => 1
            [color] => red
        )

    [1] => Array
        (
            [id] => 2
            [color] => blue
        )

    [2] => Array
        (
            [id] => 3
            [color] => green
        )

    [3] => Array
        (
            [id] => 4
            [color] => blue
        )

    [4] => Array
        (
            [id] => 5
            [color] => purple
        )

)