Home > Backend Development > PHP Problem > How to add elements to a two-dimensional array in php

How to add elements to a two-dimensional array in php

藏色散人
Release: 2023-03-10 17:38:02
Original
5776 people have browsed it

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) {. ..}".

How to add elements to a two-dimensional array in php

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

Function

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.

Code

$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);
Copy after login

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)
}
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template