How PHP gets a set of keys in a two dimensional array

  • 2021-06-28 11:38:33
  • OfStack

This is code sharing. I also see some "Taurus" code in my work to share.

Specifically, the following 2-dimensional array is read from the library.

Code List:
 
$user = array( 
0 => array( 
'id' => 1, 
'name' => ' Zhang 3', 
'email' => 'zhangsan@sina.com', 
), 
1 => array( 
'id' => 2, 
'name' => ' plum 4', 
'email' => 'lisi@163.com', 
), 
2 => array( 
'id' => 5, 
'name' => ' king 5', 
'email' => '10000@qq.com', 
), 
...... 
); 

The above array format, you have played PHP+MYSQL, you must be very familiar with it.

So now there are two requirements:

1) Get the set of index "id" and save it as a 1-bit array to get array (1,2,5)

Don't know what your friends will do?

If I used to write directly foreach, then array_push 1 to 1 array variable.This can also be done.However, this writing can have a performance impact, since using PHP native functions is certainly more efficient than looping.

Code List:
 
$ids = array(); 
$ids = array_map('array_shift', $user); 

With the code above, we can get the result we want. You can read the manual about using the function.

There's actually another solution here, using 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 way, the efficiency will certainly be higher.

2) Get the set of index "name" and save it as a 1-digit array to get array ('Zhang 3','Li 4','Wang 5')

As I used to write, it's the same foreach, then array_push 1 to 1 array variable.See the list of efficient codes.

Code List:
 
$names = array(); 
$names = array_reduce($user, create_function('$v,$w', '$v[$w["id"]]=$w["name"];return $v;')); 

Result:
 
array( 
1 => ' Zhang 3', 
2 => ' plum 4', 
5 => ' king 5', 
); 

Often foreach's children's shoes, correct them quickly!

Related articles: