PHP obtains a set of keys in a two-dimensional array. This article shares the code. It also shows some "Daniel" code at work for sharing. Specifically, for example, the next two-dimensional array is read from the database. Code List: $ userarray (0 & gt; array (id & gt; 1, name & gt; Zhang San, email PHP to get a set of keys in a two-dimensional array
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:
$ User = array (0 => array ('id' => 1, 'name' => 'Zhang San', 'Email '=> [email protected]',), 1 => array ('id' => 2, 'name' => 'Lily', 'e-mail '=> [email protected]',), 2 => array ('id' => 5, 'name' => 'Wang Wu ', 'email '=> [email protected]',), ......);
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:
$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:
$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:
$names = array();$names = array_reduce($user, create_function('$v,$w', '$v[$w["id"]]=$w["name"];return $v;'));
Expected result:
Array (1 => 'Zhang San', 2 => 'Li Si', 5 => 'Wang Wu ',);
Often foreach's children's shoes. please correct them!
This article is from CSDN. For more information, see the source! Http://blog.csdn.net/liruxing1715/article/details/22925575