将多维数组转换为一维时保留键

时间:2019-08-22 19:42:21

标签: php

我不知道如何正确地展平此数组。因此,当我使用array_unique展平时,我松开了键。所以,这是原始数组:

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

谢谢。

1 个答案:

答案 0 :(得分:1)

获取内部数组的键和值,并将其用作结果的键和值。

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