Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将集合中的键转换为值_Php_Arrays - Fatal编程技术网

Php 将集合中的键转换为值

Php 将集合中的键转换为值,php,arrays,Php,Arrays,我有一个这样的结构: $arr=[ “a”=>[ 0=>“bar11”, 1=>“bar12”, ], “b”=>[ 0=>“baz11”, 1=>“baz12”, ] ]; 我需要转换我的数组以获得如下内容: [0]=>数组 ( [a] =>“bar11”, [b] =>“baz11”, ) [1] =>阵列 ( [a] =>“bar12”, [b] =>“baz12”, ) php中是否有执行此转换的函数,或者如何手动执行以解决此问题? 问候 您可以通过下面的代码轻松地做到这一点 $ar

我有一个这样的结构:

$arr=[
“a”=>[
0=>“bar11”,
1=>“bar12”,
],
“b”=>[
0=>“baz11”,
1=>“baz12”,
]
];
我需要转换我的数组以获得如下内容:

[0]=>数组
(
[a] =>“bar11”,
[b] =>“baz11”,
)
[1] =>阵列
(
[a] =>“bar12”,
[b] =>“baz12”,
)
php中是否有执行此转换的函数,或者如何手动执行以解决此问题?
问候

您可以通过下面的代码轻松地做到这一点

$arr = [
  'a' => [
     0 => 'bar11',
     1 => 'bar12',
  ],
  'b'=> [
     0 => 'baz11',
     1 => 'baz12',
  ]
];
$result = array();

foreach($arr as $k1 => $value){ // $k1 will contain a, b, ....etc
    foreach($value as $k2 =>$val){ // $k2 contain 0 and 1
        // swap index here like [0][a], [0][b] , [1][a] ...... to get your required result  
        $result[$k2][$k1] = $val; 
    }
}
如果外部数组中的所有数组大小相同,则上面的代码可以工作,我们只需交换内部数组和外部数组的键即可获得所需的结果


a和b中的数组是否总是大小相同?这是一个重复的问题,您没有尝试自行解决,因此我已记录了此问题。好的,我将做一个explanation@mickmackusa我希望我在代码中的评论将有助于理解11年前的代码完全相同的答案:如果你撤回你的答案,Stack Overflow的自动脚本(Roomba)将能够清除此冗余页面,而无需任何额外的人工交互。(其他两个答案已经这样做了。)那么我应该撤回这个吗?