This article for code sharing, but also in the work to see some "Daniel" code, do share.
Specifically, such as the next two-dimensional array, is read from the library.
Code listings:
Copy Code code as follows:
$user = Array (
0 => Array (
' ID ' => 1,
' Name ' => ' John ',
' Email ' => ' zhangsan@sina.com ',
),
1 => Array (
' ID ' => 2,
' Name ' => ' Dick ',
' Email ' => ' lisi@163.com ',
),
2 => Array (
' ID ' => 5,
' Name ' => ' Harry ',
' Email ' => ' 10000@qq.com ',
),
......
);
The above array format, the main people have played php+mysql, must be very familiar with.
So, now there are two of these requirements:
1 Gets the collection of the index "ID" and saves it as an array, that is, the array (1,2,5)
I do not know how the friends will write it?
If it was previously my writing is directly foreach, and then Array_push one after another into an array variable plug. This can also be achieved. But this style of writing affects performance because using PHP's native functions is certainly more efficient than looping.
Code listings:
Copy Code code as follows:
$ids = Array ();
$ids = Array_map (' Array_shift ', $user);
The code can get the results we want, and we want to see the manual for the use of the function.
In fact, there is also a scheme, using the Array_column function, but this function requires PHP version requirements, (PHP 5 >= 5.5.0)
Code listings:
Copy Code code as follows:
$ids = Array ();
$ids = Array_column ($user, ' id ');
In that case, the efficiency will certainly be higher.
2 Gets the collection of index "name" and saves it as an array that gets array (' John ', ' Dick ', ' Harry ')
According to my previous writing, it's still the same foreach, and then Array_push each one into an array variable. See the efficient code list.
Code listings:
Copy Code code as follows:
$names = Array ();
$names = Array_reduce ($user, Create_function (' $v, $w ', ' $v ["id"]]= $w [' name '];return $w; ')];
Get the result:
Copy Code code as follows:
Array
1 => ' John ',
2 => ' Dick ',
5 => ' Harry ',
);
Often foreach children's shoes, quickly corrected it!