Home > Software design >  php - how to flatten a nested array via array_map?
php - how to flatten a nested array via array_map?

Time:09-29

I have this:

<?php

$blocks = [
    [
        "id" => 1,
        "content" => "foo",
    ],
    [
        "id" => 2,
        "content" => "bar",
    ],
    [
        [
            "id" => 3,
            "content" => "foo",
        ],
        [
            "id" => 4,
            "content" => "qux",
        ],
    ],
    [
        "id" => 5,
        "content" => "waldo",
    ],
    [
        "id" => 6,
        "content" => "foo",
    ],
];

$out = array_map(function ($block) {
    return $block["content"];
}, $blocks);

print_r($out);

which outputs:

Array
(
    [0] => foo
    [1] => bar
    [2] => 
    [3] => waldo
    [4] => foo
)

(and an undefined index error)

How do I adjust it to flatten the nested items? Duplicates must remain, and the relative order must be retained, producing:

Array
(
    [0] => foo
    [1] => bar
    [2] => foo
    [3] => qux
    [4] => waldo
    [5] => foo
)

CodePudding user response:

You can archive it by using array_walk_recursive and unset

array_walk_recursive($blocks, static function ($item, $key) use (&$result) {$result[$key][] = $item;});
unset($result['id']);

In array_walk_recursive($blocks, static function..... it will produce array-like

enter image description here

with unset($result['id']); output is

enter image description here


or even shorter

array_walk_recursive($blocks, static function ($item, $key) use (&$result) {
    if ($key === 'content') {
        $result[] = $item;
    }
});

CodePudding user response:

This should be work fine.

    <?php

   $blocks = [
    [
        "id" => 1,
        "content" => "foo",
    ],
    [
        "id" => 2,
        "content" => "bar",
    ],
    [
        [
            "id" => 3,
            "content" => "foo",
        ],
        [
            "id" => 4,
            "content" => "qux",
        ],
    ],
    [
        "id" => 5,
        "content" => "waldo",
    ],
    [
        "id" => 6,
        "content" => "foo",
    ],
];

   
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($blocks));

foreach($iterator as $key=>$value)
{
    if($key === "content") {
        $newArray[] = $value;
    }
}

var_dump($newArray);

?>
  • Related