views:

24

answers:

2

What would be the best way to extract a column out of mysql results set? My result set is like:

[0] = ('id'=>1, 'name'=>a),
[1] = ('id'=>2, 'name'=>b),
[2] = ('id'=>3, 'name'=>c)

How can I extract 'name' column as an array from this? I can do it using for loop. But wondering if there are any better reusable solution?

A: 
$rows = array(
 array('id'=>1, 'name'=>'a'), 
 array('id'=>2, 'name'=>'b'),
 array('id'=>3, 'name'=>'c')
);


$names = array();    
foreach ($rows as $row) {
 $names[] = $row['name'];
}

Using a simple loop will execute much faster than using something like array_map (which incurs much more overhead). Difference in speed can be as much as 100%.

webbiedave
+2  A: 

You could use array_map to do this.

function getName($elem) {
  return $elem['name'];
}
$names = array_map('getName', $input);

// PHP 5.3.0 or higher allows anonymous functions
$names = array_map(function($e) { return $e['name']; }, $input);
gnarf
+1, this *or* `array_walk` would be the way to go, `array_map` is however, slightly easier to use.
karim79
`array_map` won't destroy the original array either... Walk will... http://php.net/manual/en/function.array-walk.php is the documentation page for `array_walk`
gnarf