Capfer
Capfer

Reputation: 901

Preserve keys when convert multi dimensional array to one dimensional

I can't figure out how to correctly flatten this array. So, I loose the keys when I flattened using array_unique. So, This is the original array:

  array:9 [
  0 => array:1 [
    2 => "Opnam"
  ]
  1 => array:1 [
    2 => "Opnam"
  ]
  2 => array:1 [
    2 => "Opnam"
  ]
  3 => array:1 [
    3 => "Voem"
  ]
  4 => array:1 [
    8 => "And"
  ]
  5 => array:1 [
    6 => "Vei"
  ]
  6 => array:1 [
    6 => "Vei"
  ]
  7 => array:1 [
    8 => "And"
  ]
  8 => array:1 [
    8 => "And"
  ]
]

The is the expected output:
array:[
  2 => "Opnam"
  3 => "Voem"
  6 => "Vei"
  8 => "And"
]

Thanks in advance.

Upvotes: 0

Views: 62

Answers (1)

Barmar
Barmar

Reputation: 781917

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;
    }
}

Upvotes: 1

Related Questions