Search code examples
phpmultidimensional-arrayindexingarray-merge

How to merge first level keys with their second level values and remove all associative keys?


I have array like this :

Array (
    [2018-03-12] => Array (
        [United States] => 4
        [Australia] => 15
        [United Kingdom] => 0
        [New Zealand] => 0
    )
    [2018-03-13] => Array (
        [United States] => 0
        [Australia] => 8
        [United Kingdom] => 2
        [New Zealand] => 0
    )
)

I want to make an array like this:

[
    ["2018-03-12", 4, 15, 0, 0],
    ["2018-03-13", 0, 8, 0, 2]
]

How can this be done?


Solution

  • Try:

    $arr = [
        '2018-03-12' => [
            'United States' => 4,
             'Australia' => 15,
             'United Kingdom' => 0,
             'New Zealand' => 0,
        ],
        '2018-03-13' => [
             'United States' => 0,
             'Australia' => 8,
             'United Kingdom' => 2,
             'New Zealand' => 0,
        ]
    ];
    
    return array_map(function ($item, $key) {
        return array_merge([$key], array_values($item));
    },$arr, array_keys($arr));
    

    Demo https://implode.io/K8yHG0