PHP gets the collection of a key in a two-dimensional array
This article for code sharing, but also in the work to see some "Daniel" code, do share.
Specifically, the next two-dimensional array is read from the library.
Code Listing:
$user = Array ( 0 = = Array ( ' id ' = = 1, ' name ' = ' Zhang San ', ' email ' + = [email protected] ' , ), 1 = = Array ( ' id ' = = 2, ' name ' = ' John Doe ', ' email ' = [email protected] ', ), 2 = = Array ( ' id ' = = 5, ' name ' = ' Harry ', ' email ' + = [email protected ]', ), ......);
The above array format, the main people have played php+mysql, it must be very familiar with.
Well, now there are two requirements:
1) Get the collection of index "ID" and save it as an array, that is, get Array (1,2,5)
Do not know what friends will write?
If it was before my writing is direct foreach, and then array_push to an array variable into the plug. This can also be achieved. But this kind of writing affects performance, because using PHP's native functions is certainly more efficient than looping.
Code Listing:
$ids = Array (); $ids = Array_map (' Array_shift ', $user);
As the above code can get the results we want, about the use of functions want to read the manual.
In fact, there is a solution, using the Array_column function, but this function requires PHP version requirements, (PHP 5 >= 5.5.0)
Code Listing:
$ids = Array (); $ids = Array_column ($user, ' id ');
In that case, the efficiency will certainly be higher.
2) get the collection of index "name" and save it as an array, that is, get the array (' Zhang San ', ' John Doe ', ' Harry ')
According to my previous writing, the same foreach, and then array_push to an array variable in the plug. See the efficient code listing.
Code Listing:
$names = Array (), $names = Array_reduce ($user, Create_function (' $v, $w ', ' $v [$w ["id"]]= $w ["name"];return $v; ')];
Get results:
Array ( 1 = ' Zhang San ', 2 = ' John Doe ', 5 = ' Harry ',);
Often foreach children's shoes, quickly correct it!
This article from CSDN, reprint please indicate the source! http://blog.csdn.net/liruxing1715/article/details/22925575