php 如何在php5中将二维数组转换为一维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8754980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert two dimensional array to one dimensional array in php5
提问by DEVOPS
Possible Duplicate:
Turning multidimensional array into one-dimensional array
可能的重复:
将多维数组转换为一维数组
I have this kind of an array
我有这种数组
Array
(
[0] => Array
(
[0] => 88868
)
[1] => Array
(
[0] => 88867
)
[2] => Array
(
[0] => 88869
)
[3] => Array
(
[0] => 88870
)
)
I need to convert this to one dimensional array. How can I do that?
我需要将其转换为一维数组。我怎样才能做到这一点?
For example like this..
比如像这样..
Array
(
[0] => 88868
[1] => 88867
[2] => 88869
[3] => 88870
)
Any php built in functionality is available for this array conversion?
任何 php 内置功能可用于此数组转换?
回答by deceze
For your limited use case, this'll do it:
对于您有限的用例,这将做到:
$oneDimensionalArray = array_map('current', $twoDimensionalArray);
This can be more generalized for when the subarrays have many entries to this:
当子数组有许多条目时,这可以更概括:
$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);
回答by hakre
The PHP array_merge
Docsfunction can flatten your array:
PHP array_merge
Docs函数可以展平您的数组:
$flat = call_user_func_array('array_merge', $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:
如果原始数组的深度高于 2 级,PHP 中的 SPL 有一个RecursiveArrayIterator
可以用来展平它:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);
See as well:Turning multidimensional array into one-dimensional array
另请参阅:将多维数组转换为一维数组
回答by redmoon7777
try:
尝试:
$new_array = array();
foreach($big_array as $array)
{
foreach($array as $val)
{
array_push($new_array, $val);
}
}
print_r($new_array);
回答by marioosh
$oneDim = array();
foreach($twoDim as $i) {
$oneDim[] = $i[0];
}
回答by benesch
Yup.
是的。
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];