将单元素数组的数组转换为一维数组
我有这种包含单元素数组的数组:
$array = [[88868], [88867], [88869], [88870]];
我需要将其转换为一维数组。
期望的输出:
[88868, 88867, 88869, 88870]
是否有任何内置/本机 PHP 功能可用于此数组转换?
I have this kind of an array containing single-element arrays:
$array = [[88868], [88867], [88869], [88870]];
I need to convert this to one dimensional array.
Desired output:
[88868, 88867, 88869, 88870]
Is there any built-in/native PHP functionality for this array conversion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
对于您有限的用例,这可以做到:
当子数组有很多条目时,这可以更通用:
For your limited use case, this'll do it:
This can be more generalized for when the subarrays have many entries to this:
PHP
array_merge
文档函数可以展平你的数组:如果原始数组的深度高于 2 层,PHP 中的 SPL 有一个
RecursiveArrayIterator
您可以使用它来展平它:另请参阅: 将多维数组变成一维数组
The PHP
array_merge
Docs function can flatten your array:In case the original array has a higher depth than 2 levels, the SPL in PHP has a
RecursiveArrayIterator
you can use to flatten it:See as well: Turning multidimensional array into one-dimensional array
尝试:
try:
是的。
http://codepad.org/f9KjbCCb
Yup.
http://codepad.org/f9KjbCCb
对于二维数组,这也适用:
array_merge(...$twoDimensionalArray)
For a two dimensional array this works as well:
array_merge(...$twoDimensionalArray)
虽然之前用于关闭此页面的页面上的一些答案 确实有适合这个问题的答案(例如 array_merge(...$array) )。由于输入数据结构的原因,针对这个特定问题的一些技术不属于其他页面。
这里的示例数据结构是单元素索引数组的数组。
这就是这个问题所需要的一切。
如果您曾经有过一次愚蠢的工作面试,要求您在不调用任何函数的情况下进行面试,您可以使用语言构造 (
foreach()
) 并使用“数组解构”语法将值推入结果中变量甚至无需为循环编写主体。 (演示)Laravel 还有一个扁平化辅助方法:Arr::flatten()
While some of the answers on the page that was previously used to close this page did have answers that suited this question (like
array_merge(...$array)
). There are techniques for this specific question that do not belong on the other page because of the input data structure.The sample data structure here is an array of single-element, indexed arrays.
Is all that this question requires.
If you ever have a daft job interview that asks you to do it without any function calls, you can use a language construct (
foreach()
) and use "array destructuring" syntax to push values into a result variable without even writing a body for the loop. (Demo)Laravel also has a flattening helper method: Arr::flatten()