部分展平多维数组
将数组转换为以下形式的好方法是什么
Array (
[0] = Array (
[0] = Array (
[key] = val
[key2] = val2
)
)
[1] = Array (
[0] = Array (
[key] = val
[key2] = val2
)
)
)
:
Array (
[0] = Array (
[key] = val
[key] = val2
)
[1] = Array (
[key] = val
[key] = val2
)
)
What would be a good way to transform an array that looks like:
Array (
[0] = Array (
[0] = Array (
[key] = val
[key2] = val2
)
)
[1] = Array (
[0] = Array (
[key] = val
[key2] = val2
)
)
)
to
Array (
[0] = Array (
[key] = val
[key] = val2
)
[1] = Array (
[key] = val
[key] = val2
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这可能是一种相当简洁的方法,
它使用 array_map 来调用 array_shift 在输入数组的每个元素上,这将为您提供每个子数组的第一个元素!漂亮的小单线,不是吗?
虽然很好,但效率并不是很高,因为 array_shift 做了比我们需要的更多的工作 - 一个简单的循环实际上要快得多(我刚刚对一个包含 1000 个元素的数组做了一个快速基准测试,这大约快了 6 倍)
This might be a rather neat way of doing it
This uses array_map to call array_shift on each each element of the input array, which will give you the first element of each sub-array! Nice little one-liner, no?
Nice as it is, it's not terribly efficient as array_shift does more work than we need - a simple loop is actually far faster (I just did a quick benchmark on an array with 1000 elements and this was around 6x faster)
如果您的数组是
$my_array
并且有 2 个元素,您可以:希望有所帮助。
If your array is
$my_array
and has 2 elements, you can:Hope that helped.
我想大家都想多了。这正是 array_column() 的作用。
代码:(演示)
输出:
I think everyone over thought this one. This is exactly what
array_column()
does.Code: (Demo)
Output: