有没有更好的方法来转置 PHP 2D 数组? [英] Is there better way to transpose a PHP 2D array?

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

问题描述

根据PHP手册,调用带有 NULL 回调的 array_map 导致它执行zip"函数,从给定的数组创建一个由并行元素组成的数组.

例如:

array_map(NULL,array(1,2,3),array('a','b','c'));

收益

array(array(1,'a'),array(2,'b'),array(3,'c'))

这也相当于转置数组

array(array(1,2,3),array('a','b','c'))

现在,这似乎是您可以转置数组的最接近的方法(使用内置函数),除了 array_map 需要一个数组列表,而不是一个数组数组.>

在我正在处理的一些代码中,我需要转置一个数组数组,而不是一个数组列表,所以我做了这个解决方法:

call_user_func_array('array_map',array_merge(array(NULL),$array_of_arrays))

然而,这感觉很脏很笨拙.

所以我问:
除了自定义实现之外,是否有更好的方法来使用 PHP 转置二维数组?

解决方案

不.那是最优雅的.

According to the PHP Manual, calling array_map with a NULL callback causes it to perform a "zip" function, creating an array of arrays of parallel elements from the given arrays.

For example:

array_map(NULL,array(1,2,3),array('a','b','c'));

yields

array(array(1,'a'),array(2,'b'),array(3,'c'))

This is also equivalent to transposing the array

array(array(1,2,3),array('a','b','c'))

Right now, it appears this is the closest way (using built-in functions) you can transpose an array, except that array_map takes a list of arrays, not an array of arrays.

In some code I am working on, I need to transpose an array of arrays, not a list of arrays, so I made this work-around:

call_user_func_array('array_map',array_merge(array(NULL),$array_of_arrays))

However, this feels very dirty and clumsy.

And so I ask:
Is there a better way to transpose a 2D array with PHP, aside from a custom implementation?

解决方案

Nope. That's the most elegant.

这篇关于有没有更好的方法来转置 PHP 2D 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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