0

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"
]
0

2 Answers 2

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Simply spread the rows inside of array_replace(). Differently from array_merge(), array_replace() will preserve the keys found in the second level. Demo

var_export(array_replace(...$array));

Output:

array (
  2 => 'Opnam',
  3 => 'Voem',
  8 => 'And',
  6 => 'Vei',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.