如何在 PHP 中将多维数组“展平”为简单数组?

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

How to "flatten" a multi-dimensional array to simple one in PHP?

phparraysmultidimensional-array

提问by Adriana

It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with str_splitto make new simple array. However I never know if the join pattern isn't also in values and so after doing str_splitmy original values could break.

这可能是初学者的问题,但我已经阅读了更长时间的文档,但找不到任何解决方案。我想我可以对每个维度使用内爆,然后将这些字符串放回一起str_split以创建新的简单数组。但是,我永远不知道连接模式是否也在值中,因此在执行str_split我的原始值之后可能会中断。

Is there something like combine($array1, $array2)for arrays inside of multi-dimensional array?

combine($array1, $array2)多维数组中的数组是否有类似的东西?

采纳答案by Luc M

Use array_walk_recursive

array_walk_recursive

<?php

$aNonFlat = array(
    1,
    2,
    array(
        3,
        4,
        5,
        array(
            6,
            7
        ),
        8,
        9,
    ),
    10,
    11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

var_dump($objTmp->aFlat);

/*
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
  [10]=>
  int(11)
}
*/

?>

Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)

使用 PHP 5.5.9-1ubuntu4.24 (cli) 测试(构建时间:2018 年 3 月 16 日 12:32:06)

回答by Prasanth Bendra

$array  = your array

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);

REF: http://php.net/manual/en/function.call-user-func-array.php

参考:http: //php.net/manual/en/function.call-user-func-array.php

Here is another solution (works with multi-dimensional array) :

这是另一个解决方案(适用于多维数组):

function array_flatten($array) {

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

}

$array  = Your array

$result = array_flatten($array);

echo "<pre>";
print_r($result);

回答by Arnold Roa

This is a one line, SUPER easy to use:

这是一行,超级好用:

$result = array();
array_walk_recursive($original_array,function($v) use (&$result){ $result[] = $v; });

It is very easy to understand, inside the anonymous function/closure. $vis the value of your $original_array.

在匿名函数/闭包中很容易理解。$v是你的价值$original_array

回答by upallnite

// $array = your multidimensional array

$flat_array = array();

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k=>$v){

$flat_array[$k] = $v;

}

Also documented: http://www.phpro.org/examples/Flatten-Array.html

还记录在案:http: //www.phpro.org/examples/Flatten-Array.html

回答by Josh Johnson

If you specifically have an array of arrays that doesn't go further than one level deep (a use case I find common) you can get away with array_mergeand the splat operator.

如果您特别有一个数组数组,其深度不超过一个级别(我发现一个用例很常见),您可以使用array_mergesplat 运算符。

<?php

$notFlat = [[1,2],[3,4]];
$flat = array_merge(...$notFlat);
var_dump($flat);

Output:

输出:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}

The splat operator effectively changes the array of arrays to a list of arrays as arguments for array_merge.

splat 运算符有效地将数组数组更改为数组列表作为 的参数array_merge

回答by chaos

function flatten_array($array, $preserve_keys = 0, &$out = array()) {
    # Flatten a multidimensional array to one dimension, optionally preserving keys.
    #
    # $array - the array to flatten
    # $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
    # $out - internal use argument for recursion
    foreach($array as $key => $child)
        if(is_array($child))
            $out = flatten_array($child, $preserve_keys, $out);
        elseif($preserve_keys + is_string($key) > 1)
            $out[$key] = $child;
        else
            $out[] = $child;
    return $out;
}

回答by SamGoody

Another method from PHP's user comments(simplified) and here:

来自 PHP用户评论的另一种方法(简化)和这里

function array_flatten_recursive($array) { 
   if (!$array) return false;
   $flat = array();
   $RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
   foreach ($RII as $value) $flat[] = $value;
   return $flat;
}

The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:

这种方法的最大好处是它可以跟踪递归的深度,如果您在展平时需要的话。
这将输出:

$array = array( 
    'A' => array('B' => array( 1, 2, 3)), 
    'C' => array(4, 5) 
); 
print_r(array_flatten_recursive($array)); 

#Returns: 
Array ( 
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
)

回答by hisa_py

In PHP>=5.3 and based on Luc M's answer (the first one) you can make use of closures like this

在 PHP>=5.3 中并基于 Luc M 的回答(第一个),您可以使用这样的闭包

array_walk_recursive($aNonFlat, function(&$v, $k, &$t){$t->aFlat[] = $v;}, $objTmp);

I love this because I don't have to surround the function's code with quotes like when using create_function()

我喜欢这个,因为我不必像使用 create_function() 那样用引号将函数的代码括起来

回答by phihag

A non-recursive solution (but order-destroying):

非递归解决方案(但破坏订单):

function flatten($ar) {
    $toflat = array($ar);
    $res = array();

    while (($r = array_shift($toflat)) !== NULL) {
        foreach ($r as $v) {
            if (is_array($v)) {
                $toflat[] = $v;
            } else {
                $res[] = $v;
            }
        }
    }

    return $res;
}

回答by kelunik

With PHP 7, you can use generators and generator delegation (yield from) to flatten an array:

在 PHP 7 中,您可以使用生成器和生成器委托 ( yield from) 来展平数组:

function array_flatten_iterator (array $array) {
    foreach ($array as $value) {
        if (is_array($value)) {
            yield from array_flatten_iterator($value);
        } else {
            yield $value;
        }
    }
}

function array_flatten (array $array) {
    return iterator_to_array(array_flatten_iterator($array), false);
}

Example:

例子:

$array = [
    1,
    2,
    [
        3,
        4,
        5,
        [
            6,
            7
        ],
        8,
        9,
    ],
    10,
    11,
];    

var_dump(array_flatten($array));

http://3v4l.org/RU30W

http://3v4l.org/RU30W