开发者

how to extract a column from mysql result set?

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?


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);


$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%.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜