Search code examples
phparraysmultidimensional-arrayflattenarray-merge

Flatten 3rd level of array to create indexed array of associative rows


I have the following problem:

I have an php array looking like this:

$array = [
    [
        ['sales_count' => '2'],
        ['customer_id' => '1'],
    ],
    [
        ['sales_count' => '3'],
        ['customer_id' => '2'],
    ]
];

Now if I use json_encode on this array, I get the following result:

[[{"sales_count":"2"},{"customer_id":"1"}],[{"sales_count":"3"},{"customer_id":"2"}]] 

However, I'm trying to get the following output: (an array of flat, associative arrays)

[{"sales_count":"2","customer_id":"1"},{"sales_count":"3","customer_id":"2"}]

Solution

  • To flatten the deep associative data in each "row", none of the previous answers work as required. Other techniques provided merely flatten the data to become an array of single-element associative rows (or worse destroy associative relationships while flattening). For the record, dynamically flattening an array's first level is more succinctly coded as array_merge(...$array).

    Instead, you must iterate all rows and specifically merge their subarrays. This will flatten the deep structure only so that rows now have two associative elements. THIS is what the question is actually asking for.

    Code: (Demo)

    echo json_encode(
             array_map(
                 fn($a) => array_merge(...$a),
                 $array
             )
         );