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

前端 未结 23 2140
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:03

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 dimensio

23条回答
  •  失恋的感觉
    2020-11-22 01:13

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

    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

提交回复
热议问题