我有这样的数组。
Array (
[0]=> array("a","b")
[1]=> array("c","d")
)
我想将其转换为
Array (
[a]=> "0",
[b]=>"0",
[C]=>"1",
[d]=>"1"
)
我怎样才能以更好的方式做到这一点?
答案 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_keys
,array_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);
?>
输出是:
Array
(
[a] => 0
[b] => 0
[c] => 1
[d] => 1
)
答案 2 :(得分:0)
使用array_values
,array_fill_keys
和array_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
)