php 从数组和合并节点集中删除父级数组

2022-08-30 22:39:43

我对操纵数组很糟糕...给定此结构,我想删除顶级数组并将所有子集合并到一个平面数组中:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => hey.com
                )

            [1] => Array
                (
                    [0] => you.com
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [0] => this.com
                )

            [1] => Array
                (
                    [0] => rocks.com
                )
        )
)

到所需结构:

Array
    (
        [0] => hey.com
        [1] => you.com
        [2] => this.com
        [3] => rocks.com
    )

速度至关重要 - 我们将处理数十万个结果


答案 1
$flat = call_user_func_array('array_merge', $arr);

这将使数组平展一个级别。它将采用您提供的示例输入,并生成您请求的所需输出。

*注意 - 在此答案发布后编辑了问题。该问题先前要求获得以下所需结果:

Array
(
    [0] => Array
        (
            [0] => hey.com
            [1] => you.com
            [2] => this.com
            [3] => rocks.com
        )

)

这就是上面的答案所提供的。array_merge()

确保:

  1. 父数组使用数字索引
  2. 父数组至少有一个子元素,否则由于抱怨没有参数,您将收到php错误。array_merge

对于那些想知道它是如何工作的:

// with 
$arr = [ [1,2,3], [4,5,6] ];
// call_user_func_array('array_merge', $arr) is like calling
array_merge($arr[0], $arr[1]);

// and with 
$arr = [ [1,2,3], [4,5,6], [7,8,9] ];
// then it's like:
array_merge($arr[0], $arr[1], $arr[2]);
// and so on...

如果您使用的是 php 5.6+,则 splat 运算符 () 可以采用更具可读性的方式执行此操作:...

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

如果要按多个级别平展,则可以使用多个嵌套调用,或者要递归完全展平结构:array_merge()

// This is a great option if you don't know what depth the structure may be,
// or if the structure may contain different arrays with different depths.
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)));

答案 2

您可以使用RecursiveArrayIterator

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$list = iterator_to_array($it,false);
var_dump($list);

输出

array (size=4)
  0 => string 'hey.com' (length=7)
  1 => string 'you.com' (length=7)
  2 => string 'this.com' (length=8)
  3 => string 'rocks.com' (length=9)

观看简单演示