This article is for code sharing. I also see some "Daniel" code at work and share it with me.
Specifically, for example, the next two-dimensional array is read from the database.
Code List:
Copy codeThe Code is as follows:
$ User = array (
0 => array (
'Id' => 1,
'Name' => 'zhang san ',
'Email '=> 'zhangsan @ sina.com ',
),
1 => array (
'Id' => 2,
'Name' => 'Li si ',
'Email '=> 'lisi @ 163.com ',
),
2 => array (
'Id' => 5,
'Name' => 'wang 5 ',
'Email '=> '2017 @ qq.com ',
),
......
);
The above array format is familiar with PHP + MYSQL.
Now there are two requirements:
1) obtain the index "id" set and save it as an array to obtain array (, 5)
I don't know what your friends will do?
If I used to write foreach directly, then array_push one by one into an array variable. This can also be achieved. However, such writing affects performance, because using native PHP functions is certainly more efficient than looping.
Code List:
Copy codeThe Code is as follows:
$ Ids = array ();
$ Ids = array_map ('array _ shift ', $ user );
The above code can get the desired result. For more information about function usage, see the manual.
In fact, there is also a solution to use the array_column function, but this function requires PHP version requirements (PHP 5> = 5.5.0)
Code List:
Copy codeThe Code is as follows:
$ Ids = array ();
$ Ids = array_column ($ user, 'id ');
In this case, the efficiency will certainly be higher.
2) obtain the set of index "name" and save it as an array to obtain the array ('zhang san', 'Li si', 'wang wu ')
According to my previous writing method, I still use the same foreach method. Then, array_push is pushed one by one to an array variable. Please refer to the efficient code list.
Code List:
Copy codeThe Code is as follows:
$ Names = array ();
$ Names = array_reduce ($ user, create_function ('$ v, $ W',' $ v [$ w ["id"] = $ w ["name"]; return $ v ;'));
Expected result:
Copy codeThe Code is as follows:
Array (
1 => 'zhang san ',
2 => 'Li si ',
5 => 'wang wu ',
);
Often foreach's children's shoes. Please correct them!