PHP arrays. Put an array of singleton arrays in one array.

Using a proprietary structure, I often find myself in a situation where I get a result set from a database in the following format:

array(5) { [0] => array(1) { ["id"] => int(241) } [1] => array(1) { ["id"] => int(2) } [2] => array(1) { ["id"] => int(81) } [3] => array(1) { ["id"] => int(560) } [4] => array(1) { ["id"] => int(10) } } 

I would prefer to have a single array of identifiers, for example:

 array(5) { [0] => int(241) [1] => int(2) [2] => int(81) [3] => int(560) [4] => int(10) } 

To get there, I often find that I write:

 $justIds = array(); foreach( $allIds as $id ) { $justIds[] = $id["id"]; } 

Is there a more efficient way to do this?

+7
arrays php
source share
2 answers
 $out = array_map('array_shift', $in); 

eg.

 $in = array( array("id" => 241), array ("id" => 2), array ("id" => 81), array ("id" => 560), array ("id" => 10) ); $out = array_map('array_shift', $in); var_dump($out); 

prints

 array(5) { [0]=> int(241) [1]=> int(2) [2]=> int(81) [3]=> int(560) [4]=> int(10) } 
+9
source share

With PHP 5.3 you can do

 $justIds = array_map( function($cur) { return $cur['id']; }, $allIds ); 

With PHP <5.3, you must define a regular function and then pass the name as a string to array_map ().

+6
source share

All Articles