如何在 PHP 中将多维数组翻转 90 度(转置)?例如:
// 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"
}
你会如何实施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?
即你将如何编写一个函数以便:
$foo[j][k][...][x][y][z] = $bar[z][k][...][x][y][j]
?(ps.我不认为 12 嵌套for loops
在这种情况下是最好的解决方案。)
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
或者,如果您使用 PHP 5.6 或更高版本:
function transpose($array) {
return array_map(null, ...$array);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)