php 将多维数组转化为一维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8611313/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:05:09  来源:igfitidea点击:

Turning multidimensional array into one-dimensional array

phparraysmultidimensional-array

提问by Tomi Seus

I've been banging my head on this one for a while now.

一段时间以来,我一直在关注这个问题。

I have this multidimensional array:

我有这个多维数组:

Array
(
    [0] => Array
        (
            [0] => foo
            [1] => bar
            [2] => hello
        )

    [1] => Array
        (
            [0] => world
            [1] => love
        )

    [2] => Array
        (
            [0] => stack
            [1] => overflow
            [2] => yep
            [3] => man
        )

And I need to get this:

我需要得到这个:

Array
(
    [0] => foo
    [1] => bar
    [2] => hello
    [3] => world
    [4] => love
    [5] => stack
    [6] => overflow
    [7] => yep
    [8] => man
)

Any ideas?

有任何想法吗?

All other solutions I found solve multidimensional arrays with different keys. My arrays use simple numeric keys only.

我发现的所有其他解决方案都使用不同的键来解决多维数组。我的数组只使用简单的数字键。

回答by deceze

array_reduce($array, 'array_merge', array())

Example:

例子:

$a = array(array(1, 2, 3), array(4, 5, 6));
$result = array_reduce($a, 'array_merge', array());

Result:

结果:

array[1, 2, 3, 4, 5, 6];

回答by hakre

The PHP array_merge­Docsfunction can flatten your array:

PHP array_mergeDocs函数可以展平您的数组:

$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 RecursiveArrayIteratoryou can use to flatten it:

如果原始数组的深度高于 2 级,PHP 中的 SPL 有一个RecursiveArrayIterator可以用来展平它:

$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);

See as well: How to Flatten a Multidimensional Array?.

另请参阅:如何展平多维数组?.

回答by Grexis

This is really all there is to it:

这就是它的全部内容:

foreach($array as $subArray){
    foreach($subArray as $val){
        $newArray[] = $val;
    }
}

回答by Don't Panic

As of PHP 5.6this can be done more simply with argument unpacking.

从 PHP 5.6 开始,这可以通过参数解包更简单地完成。

$flat = array_merge(...$array);

回答by n00b

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

where $a is your array name. for details

其中 $a 是您的数组名称。 详情

回答by Hamid Naghipour

As of PHP 5.3 the shortest solution seems to be array_walk_recursive() with the new closures syntax:

从 PHP 5.3 开始,最短的解决方案似乎是使用新的闭包语法的 array_walk_recursive():

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

回答by rray

In PHP5.6 there other way to solve this problem, combining the functions, array_shift()to remove the first elemente of the original array, array_pus()to add items an new array, the important thing is the of ...splapt/elipse operator it will unpack the return of array_shitf()like an argument.

在 PHP5.6 中还有其他方法可以解决这个问题,结合函数,array_shift()删除原始数组的第一个元素,array_pus()将项目添加到一个新数组中,重要的是...slapt/elipse 运算符它会解包array_shitf()like的返回一个论点。

<?php

$arr = [
        ['foo', 'bar', 'hello'],
        ['world', 'love'],
        ['stack', 'overflow', 'yep', 'man', 'wow']
    ];

$new = [];
while($item = array_shift($arr)){
    array_push($new, ...$item);
}

print_r($new);

Output:

输出:

Array
(
    [0] => foo
    [1] => bar
    [2] => hello
    [3] => world
    [4] => love
    [5] => stack
    [6] => overflow
    [7] => yep
    [8] => man
    [9] => wow
)

Example - ideone

示例 - ideone

回答by Kunwar Kishor

I had used this code to resolve same type of problem. so you can also try this.

我曾使用此代码来解决相同类型的问题。所以你也可以试试这个。

function array_flatten($array) { 

 if (!is_array($array))  
{ 
  return FALSE;  
}  
  $result = array(); 
foreach ($array as $key => $value)
{
  if (is_array($value))  
  {
   $result = array_merge($result, array_flatten($value));
  } 
  else  {
  $result[$key] = $value;   
  }  
}   
return $result; 
} 

回答by Rutunj sheladiya

This will make

这将使

array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });

回答by Roman

$blocked_dates = array(
                    '2014' => Array
                        (
                            '8' => Array
                                (
                                    '3' => '1',
                                    '4' => '1',                                     
                                    '6' => '1',                                     
                                    '10' => '1',
                                    '15' => '1',
                                    '25' => '1'

                                )

                        ),
                    '2015' => Array
                        (
                            '9' => Array
                                (
                                    '3' => '1',
                                    '4' => '1',                                    
                                    '6' => '1',                                     
                                    '10' => '1',
                                    '15' => '1',
                                    '25' => '1'

                                )

                        )    

                );

RESUTL(ONE DIMENTIONAL ARRAY) :

结果(一维数组):

$unavailable_dates = array();
foreach ($blocked_dates as $year=>$months) {

    foreach ($months as $month => $days) {

        foreach ($days as $day => $value) {

            array_push($unavailable_dates,"$year-$month-$day");
        }

    }
}



$unavailable_dates = json_encode($unavailable_dates);
print_r($unavailable_dates);

OUTPUT : ["2014-8-3","2014-8-4","2014-8-6","2014-8-10","2014-8-15","2014-8-25","2015-9-3","2015-9-4","2015-9-6","2015-9-10","2015-9-15","2015-9-25"]