如何在php中将元素添加到子数组 [英] How to add an element into subarray in php

查看:196
本文介绍了如何在php中将元素添加到子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

$main_arr = [
  0=>[
         "el 01",
         "el 02",
         "el 03",
     ],
  1=>[
         "el 11",
         "el 12",
         "el 13",
     ],
  2=>[
         "el 21",
         "el 22",
         "el 23",
     ],
];

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

Is there a function or single statement in php like ninja_array_method($main_arr, "el new") that add new element into all sub arrays to be :

$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",
     ],
];

我只想将这些元素 el new添加到所有数组中,而无需在一行中进行任何更改或类似add_el($ main_arr, el new)

I just want to add these element "el new" into all arrays without any change in one single line or just method like add_el($main_arr, "el new")

推荐答案

使用 foreach循环参考 &

foreach($data as $ind=>&$ar){
     $ar[] = 'el new';
}

演示

Demo

参考& 会突变您的子数组。

Reference & mutates your subarray.

如果需要函数:

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

演示

Demo

这篇关于如何在php中将元素添加到子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆