如何在php中匹配嵌套关联数组中的键

时间:2017-10-23 09:39:29

标签: php associative-array

所以例如我有类似

的东西
array:2 [▼
  "old" => array:2 [▼
    "uk" => "unk"
    "en" => "eng"
    "fr" => "fre"
  ]
  "new" => array:2 [▼
    "uk" => "united kingdom"
    "en" => "english"
    "fr" => "french"
  ]
]

atm我只能根据预定义的密钥获得一个项目

foreach ($data as $status => $value) {
    $str .= $value['uk'];
}

给出

unk    united kingdom

相反,我想得到所有这些,所以结果将是

unk    united kingdom
eng    english
fre    french

可以转换为数组或组合值

array:3 [▼
  "uk" => [
    "unik",
    "united kingdom"
  ],
  "en" => [
    "eng",
    "english"
  ],
  "fr" => [
    "fren",
    "french"
  ]
]

那么实现这一目标的最佳途径是什么?

2 个答案:

答案 0 :(得分:2)

您可以按照以下方式使用array_walk_recursive

$output = [];
array_walk_recursive($arr, function ($value, $key) use (&$output) {
    $output[$key][] = $value;
});

直播示例:https://3v4l.org/aKYsG

答案 1 :(得分:1)

你只需要展平子阵列:

$output = array();
foreach ($data as $status => $codeArray) {
   foreach ($codeArray as $code=>$value){
     $output[$code][]=$value;
   }
}