在 PHP 中转置多维数组 [英] Transposing multidimensional arrays in PHP

查看:38
本文介绍了在 PHP 中转置多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 PHP 中翻转 90 度(转置)多维数组?例如:

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"
}

你将如何实现 flipDiagonally()?

这不是作业.我只是想看看是否有任何 SOers 有比最明显的路线更有创意的解决方案.但既然有一些人抱怨这个问题太简单了,那么一个更通用的解决方案如何处理 nth 维数组?

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.在这种情况下,我认为 12 个嵌套的 for 循环 不是最好的解决方案.)

?(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);
}

或者,如果您使用的是 PHP 5.6 或更高版本:

Or if you're using PHP 5.6 or later:

function transpose($array) {
    return array_map(null, ...$array);
}

这篇关于在 PHP 中转置多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆