代码之家  ›  专栏  ›  技术社区  ›  Aamir

php:如何从多提及数组中创建并行数组

  •  1
  • Aamir  · 技术社区  · 7 年前

    我有这种数组

    $arr = array( 
       0 => array(
             0 => array(
                 'name' => 'test1',
                 'country' => 'abc'  
             )
             1 => array(
                 'name' => 'test2',
                 'country' => 'xyz'  
             )
       )
       1 => array(
         'name' => 'test3',
         'country' => 'pqr'
       )
    );
    

    如何使所有数组都成为并行数组。使所有子数组彼此平行,而不使用任何循环。 这样地

    $arr = array( 
           0 => array(
                     'name' => 'test1',
                     'country' => 'abc'  
                 )
           1 => array(
                     'name' => 'test2',
                     'country' => 'xyz'  
                 )
           2 => array(
                     'name' => 'test3',
                     'country' => 'pqr'
           )
        );
    

    任何帮助都非常感谢。!

    2 回复  |  直到 7 年前
        1
  •  0
  •   Andreas    7 年前

    奈杰尔代码的动态版本是循环数组并合并每个子数组。

    $new = [];
    foreach($arr as $subarr){
        $new = array_merge($new, $subarr);
    }
    var_dump($new);
    

    https://3v4l.org/np2ZD

        2
  •  0
  •   Nigel Ren    7 年前

    你可以简单地合并数组…

    $out = array_merge($arr[0], [$arr[1]]);
    print_r($out);
    

    这给了…

    Array
    (
        [0] => Array
            (
                [name] => test1
                [country] => abc
            )
    
        [1] => Array
            (
                [name] => test2
                [country] => xyz
            )
    
        [2] => Array
            (
                [name] => test3
                [country] => pqr
            )
    
    )