我们在开发过程中经常会从Mysql数据库中查询数据,然后又要对数据进行处理。
我们来讲讲处何处理要效率要高一些。
比如我们从Mysql数据库中查询出下面的二维数据:
$res = array( 0 => array( 'id' => 10, 'name' => 'PHP', ), 1 => array( 'id' => 20, 'name' => 'html', ), 2 => array( 'id' => 30, 'name' => 'mysql', ), 3 => array( 'id' => 40, 'name' => 'java', ) );
现在我们需要对上面的数组进行处理:
1)获取索引 "id"的集合、并且保存为一个数组、即得到 array(10,20,30,40)?
2)获取索引 "name"的集合、并且保存为一个数组、即得到 array('php','html','mysql','java')?
如果是以前我的写法就是直接 foreach、然后 array_push 一个个的往一个数组变量里塞。
这样也能实现、但这样的写法很影响性能、因为使用 PHP 原生的函数肯定比循环效率高。
下面是推荐大家用的写法:
<?php
$res = array(
0 => array(
'id' => 10,
'name' => 'PHP',
),
1 => array(
'id' => 20,
'name' => 'html',
),
2 => array(
'id' => 30,
'name' => 'mysql',
),
3 => array(
'id' => 40,
'name' => 'java',
)
);
# 1:获取$res二维数组中,索引id的集合
$ids = array();
$ids = array_map('array_shift', $res);
print_r($ids);
# 2:获取$res二维数组中,索引id的集合
$idss = array();
$idss = array_map(function($v){return $v['id'];}, $res);
print_r($idss);
# 3:获取$res二维数组中,索引name的集合
echo '<br/><br/><br/>';
$names = array();
$names = array_reduce($res, create_function('$v,$w', '$v[]=$w["name"];return $v;'));
print_r($names);
# 4:获取$res二维数组中,索引name的集合
$namess = array();
$namess = array_map(function($v){return $v['name'];}, $res);
print_r($namess);
/**
* 当然上面两种方法还有一种写法的,不过需要PHP版本支持:PHP 5 >= 5.5.0
* 如果要在底版本中也使用的话,我们就需要自己动手写一个array_column函数方法。
*/
if (!function_exists('array_column')) {
function array_column($array, $column_key, $index_key = null) {
$column_key_isNumber = (is_numeric($column_key)) ? true : false;
$index_key_isNumber = (is_numeric($index_key)) ? true : false;
$index_key_isNull = (is_null($index_key)) ? true : false;
$result = array();
foreach((array)$array as $key=>$val){
if($column_key_isNumber){
$tmp = array_slice($val, $column_key, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
} else {
$tmp = isset($val[$column_key]) ? $val[$column_key] : null;
}
if(!$index_key_isNull){
if($index_key_isNumber){
$key = array_slice($val, $index_key, 1);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
}else{
$key = isset($val[$index_key]) ? $val[$index_key] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
# 1:获取$res二维数组中,索引id的集合
$ids = array();
$ids = array_column($res, 'id');
print_r($ids);
# 2:获取$res二维数组中,索引name的集合
$names = array();
$names = array_column($res, 'name');
print_r($names);
?>还是在用foreach遍历的童鞋要注意了哦。
转载请注明来源地址:小川编程 » https://www.youhutong.com/index.php/article/index/172.html
1、本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,下载后请24小时内删除。
2、本站所有内容均不能保证其完整性,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用
3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意
