翻转多维数组

时间:2016-07-14 06:58:48

标签: php arrays associative-array flip

我有这样的数组。

Array (
[0]=> array("a","b")
[1]=> array("c","d")
)

我想将其转换为

Array (
[a]=> "0",
[b]=>"0",
[C]=>"1",
[d]=>"1"
)

我怎样才能以更好的方式做到这一点?

3 个答案:

答案 0 :(得分:1)

最简单的方法是使用嵌套循环。

foreach($array as $k => $arr) {
   foreach($arr as $v) {
      $result[$v] = $k;
   }
}

输出:

Array
(
 [a] => 0
 [b] => 0
 [c] => 1
 [d] => 1
)

答案 1 :(得分:0)

您只需使用array_fill_keysarray_merge

即可
<?php
$test = [0=> array("a","b"),1=> array("c","d")];
$retest = array();
foreach($test as $key=>&$value){
  $value = array_fill_keys($value, $key);
  $retest = array_merge($retest,$value);
}
print_r($retest);
?>

点击此处:https://eval.in/604948

输出是:

    Array
(
    [a] => 0
    [b] => 0
    [c] => 1
    [d] => 1
)

答案 2 :(得分:0)

使用array_valuesarray_fill_keysarray_merge函数的简短解决方案:

$arr = [
  ['a','b'],
  ['c','d'],
  ['e','f'],
];

$flipped = [];
foreach ($arr as $k => $v) {
    $flipped = array_merge($flipped, array_fill_keys(array_values($v), $k));
}

print_r($flipped); 

输出:

Array
(
    [a] => 0
    [b] => 0
    [c] => 1
    [d] => 1
    [e] => 2
    [f] => 2
)