我有这个数组:
$a = [ ["1", "2"], ["3"], ["4"], ["5", "6", "7"] ];
我需要以某种方式让它以这种方式出现:
$result = ["1", "2", "3", "4", "5", "6", "7"];
这可能是一件微不足道的事情,但我无法做到。
我已经尝试过:
$result = array_merge(...$a);
但由于某种原因,我得到了与 $a 相同的结果,根本没有变化。
用 array_merge() 是不可能做到的吗?
如何用 PHP 实现?
如果维度超过 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);