phparraysmultidimensional-arrayflattenpreserve

Preserve keys when converting a 2d array with numeric keys to a 1d array


I can't figure out how to correctly flatten this array; I lose the keys when I flatten using array_unique().

This is the original array:

[
    [2 => "Opnam"],
    [2 => "Opnam"],
    [2 => "Opnam"],
    [3 => "Voem"],
    [8 => "And"],
    [6 => "Vei"],
    [6 => "Vei"],
    [8 => "And"],
    [8 => "And"],
]

The is the expected output:

[
    2 => "Opnam"
    3 => "Voem"
    6 => "Vei"
    8 => "And"
]

Solution

  • Get the key and value of the inner array, and use it as the key and value of the result.

    $result = [];
    foreach ($original as $inner) {
        foreach ($inner as $key => $value) {
            $result[$key] = $value;
        }
    }