7

Using a proprietary framework, I am frequently finding myself in the situation where I get a resultset from the 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'd much rather have a single array of ids, such as:

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

To get there, I frequently find myself writing:

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

Is there a more efficient way to do this?

2
  • 1
    Are you using the good method? In most frameworks, there are methods like fetchCol() to handle the 1-dimensonal special cases... Commented May 31, 2010 at 16:07
  • It is the case that a fetchCol() style method is available, but in many cases I don't control what is actually fetching the information from the database (API calls etc). Commented May 31, 2010 at 16:37

2 Answers 2

9
$out = array_map('array_shift', $in);

e.g.

$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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

It would probably be more efficient to use reset instead because array_shift changes the passed array. EDIT: just tested, using 'reset' gives a 6% improvement with your example on my windows debug build.
What would a solution using reset look like?
Just replace array_shift by reset.
6

With PHP 5.3 you can do

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

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

3 Comments

Actually VolkerK's version with array_shift might be nicer than my custom callback
On the other hand this version works even if the input array contains arrays with more than one element regardless of the order. +1
I marked VolkerK's as best answer because it addresses the specific example but there are enough times where I will need to handle multi-element sub-arrays that I will be able to add both techniques to my arsenal. Thanks to you both!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.