In PHP, you can add the same field elements to all arrays through the "array_walk()" function. The code implementation statement is such as "array_walk($list, function (&$value, $key, $arr) {. ..}".
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
php How to add a two-dimensional array Element? PHP two-dimensional array append field to all arrays
In two-dimensional array, you need to add the same field to all arrays
array_walk() function to the array Apply a user-defined function to each element of the function. In the function, the key name and key value of the array are parameters.
array_walk(array,myfunction,parameter...)
Parameters | Description |
---|---|
array | Required. Specifies the array. |
myfunction | Required. The name of the user-defined function. |
parameter, ... | Optional. Specifies the parameters of the user-defined function. You can set one or more parameters for the function. |
$arr = ['age' => 11]; $list = array( ['id'=>1,'name'=>'aaa'], ['id'=>2,'name'=>'bbb'], ['id'=>3,'name'=>'ccc'] ); array_walk($list, function (&$value, $key, $arr) { $value = array_merge($value, $arr); },$arr); var_dump($list);
Output
array(3) { [0]=> array(3) { ["id"]=> int(1) ["name"]=> string(3) "aaa" ["age"]=> int(11) } [1]=> array(3) { ["id"]=> int(2) ["name"]=> string(3) "bbb" ["age"]=> int(11) } [2]=> array(3) { ["id"]=> int(3) ["name"]=> string(3) "ccc" ["age"]=> int(11) } }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add elements to a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!