如何在php中将元素添加到子数组中

Abd*_*hal 2 php arrays laravel

我有一个数组:

$main_arr = [
  0=>[
         "el 01",
         "el 02",
         "el 03",
     ],
  1=>[
         "el 11",
         "el 12",
         "el 13",
     ],
  2=>[
         "el 21",
         "el 22",
         "el 23",
     ],
];
Run Code Online (Sandbox Code Playgroud)

php 中是否有一个函数或单个语句ninja_array_method($main_arr, "el new"),将新元素添加到所有子数组中:

$main_arr = [
  0=>[
         "el 01",
         "el 02",
         "el 03",
         "el new",
     ],
  1=>[
         "el 11",
         "el 12",
         "el 13",
         "el new",
     ],
  2=>[
         "el 21",
         "el 22",
         "el 23",
         "el new",
     ],
];
Run Code Online (Sandbox Code Playgroud)

我只想将这些元素“el new”添加到所有数组中,而在一行中没有任何更改,或者只是像 add_el($main_arr, "el new") 这样的方法

Aks*_*n P 6

使用foreach loop参考 &

foreach($data as $ind=>&$ar){
     $ar[] = 'el new';
}
Run Code Online (Sandbox Code Playgroud)

演示

引用会&改变您的子数组。

如果你需要一个函数:

function add_el($data,$elem){
    foreach($data as $ind=>&$ar){
         $ar[] = $elem;
    }
    return $data;
}
Run Code Online (Sandbox Code Playgroud)

演示