移调在PHP多维数组 [英] Transposing multidimensional arrays in PHP
问题描述
您将如何翻转90度(转)PHP中的多维数组?例如:
//使用这个数组开始
$富=阵列(
'A'=>阵列(
1 => A1,
2 => 'a2',
3 => 'A3'
)
'B'=>阵列(
1 => B1,
2 => b2的,
3 => B3
)
'C'=>阵列(
1 => 'C1',
2 => 'C2',
3 => C3
)
);$巴= flipDiagonally($ foo的); //神秘功能
的var_dump($杆[2]);//所需的输出:
阵列(3){
[一] =>
串(2)A2
[B] =>
串(2)B2
[C] =>
串(2)C2
}
你将如何实施 flipDiagonally()
?
编辑:这不是功课。我只是想看看是否有任何SOers比最明显的途径更创造性的解决方案。但是,由于几个人都在抱怨这个问题是太容易了,怎么样,与正工作的更广泛的解决方案个维数组?
即。你会如何编写一个函数,因此:
$ foo的研究[J] [K] [...] [X] [Y] [Z] = $条[Z] [k]的[...] [X ] [Y] [J]。
?(PS。我不认为12嵌套 for循环
在这种情况下,最好的解决方案。)
函数转置($数组){
array_unshift($阵列,NULL);
返回call_user_func_array('array_map',$阵列);
}
或者,如果你使用PHP 5.6或更高版本:
函数转置($数组){
返回array_map(NULL,... $阵列);
}
How would you flip 90 degrees (transpose) a multidimensional array in PHP? For example:
// Start with this array
$foo = array(
'a' => array(
1 => 'a1',
2 => 'a2',
3 => 'a3'
),
'b' => array(
1 => 'b1',
2 => 'b2',
3 => 'b3'
),
'c' => array(
1 => 'c1',
2 => 'c2',
3 => 'c3'
)
);
$bar = flipDiagonally($foo); // Mystery function
var_dump($bar[2]);
// Desired output:
array(3) {
["a"]=>
string(2) "a2"
["b"]=>
string(2) "b2"
["c"]=>
string(2) "c2"
}
How would you implement flipDiagonally()
?
Edit: this is not homework. I just want to see if any SOers have a more creative solution than the most obvious route. But since a few people have complained about this problem being too easy, what about a more general solution that works with an nth dimension array?
i.e. How would you write a function so that:
$foo[j][k][...][x][y][z] = $bar[z][k][...][x][y][j]
?(ps. I don't think 12 nested for loops
is the best solution in this case.)
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
Or if you're using PHP 5.6 or later:
function transpose($array) {
return array_map(null, ...$array);
}
这篇关于移调在PHP多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!