开发者

how to extract a column from mysql result set?

开发者 https://www.devze.com 2022-12-29 19:34 出处:网络
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),

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

精彩评论

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