Share the following PHP method to get a collection of a key in a two-dimensional array.
Specifically, the next two-dimensional array is read from the library.
Code:
$user Array array' id ' = 1, ' name ' = ' Zhang San ', ' email ' = ' zhangsan@sina.com ', 'array ' ' id ' = 2, ' name ' = ' John Doe ', ' email ' = ' lisi@163.com ',' id ' =& Gt 5, ' name ' = ' Harry ', ' email ' = ' 10000@qq.com ', ... );
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)
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:
$ids Array $idsarray_map$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:
$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 high-efficiency code.
Code:
$names Array $namesarray_reduce($usercreate_function(' $v, $w ', ' $v [$w [ "id"]]= $w ["name"];return $v; ')];
Get results:
Array
1 = ' Zhang San ',
2 = ' John Doe ',
5 = ' Harry ',
);
http://www.bkjia.com/PHPjc/780023.html www.bkjia.com true http://www.bkjia.com/PHPjc/780023.html techarticle share the following PHP method to get a collection of a key in a two-dimensional array. Specifically, the next two-dimensional array is read from the library. Code: $user = Array (0 = array ...