如何将 PHP 中的多元素数组转换为数学中的非常扁平的数组?

问题描述 投票:0回答:1

我有这个数组:

$a = [ ["1", "2"], ["3"], ["4"], ["5", "6", "7"] ];

我需要以某种方式让它以这种方式出现:

$result = ["1", "2", "3", "4", "5", "6", "7"];

这可能是一件微不足道的事情,但我无法做到。

我已经尝试过:

$result = array_merge(...$a); 

但由于某种原因,我得到了与 $a 相同的结果,根本没有变化。

用 array_merge() 是不可能做到的吗?

如何用 PHP 实现?

php arrays multidimensional-array array-merge
1个回答
0
投票

如果维度超过 2,那么

$result = array_merge(...$a)
是不够的 – 你应该使用递归。

$a = [ ["1", "2"], ["3"], ["4"], ["5", ["6"], "7"] ];

function flattenArray($array) {
    $result = [];
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = array_merge($result, flattenArray($element));
        } else {
            $result[] = $element;
        }
    }
    return $result;
}

$flattenedArray = flattenArray($a);
print_r($flattenedArray);
© www.soinside.com 2019 - 2024. All rights reserved.