关闭

多层嵌套的使用要点及优化

271人阅读 评论(0) 收藏 举报


对于多层嵌套循环 应该保证在循环中的数据库查询,最好一次性都查完,不要每次都查一次数据库。。减少查询数据库的次数


尽量避免使用多层嵌套

例子:

没优化之前

if (!empty($param['register_from_group'])) {
    $register_from = explode(',', $param['register_from_group']);
    foreach ($register_from as $key => $val) {
        $user_group = self::filter_user($val, $param);
        foreach ($user_group as $k => $v) {
            $cur_user = User::model()->find('user_id=:user_id', array(':user_id' => $v->user_id));
            $user_info[$k]['user_id'] = $v->user_id;
            $user_info[$k]['phone'] = $cur_user->user_name;
            $user_info[$k]['rid'] = isset($param['rid']) ? $param['rid'] : 0;
            $user_info[$k]['id'] = $v->id;
            $user_info[$k]['sequence_id'] = $cur_user->sequence_id;
        }
        $sms = SmsCrontabConfig::model()->find('id=:id and status=1', array('id' => $param['id']));
        $sms->uptime = time();
        $sms->save();
        self::SendReward($user_info, $param);
    }
}

优化之后:
if (!empty($param['register_from_group'])) {
    $register_from = explode(',', $param['register_from_group']);
    $user_group=array();
    foreach ($register_from as $key => $val) {
        $user_group[$key] = self::filter_user($val, $param);
    }
    $user_id=array();
    foreach($user_group as $k => $v) {
        foreach($v as $ks=>$va){
            $user_id[$ks]=$va->user_id;
        }
    }

    $criteria=new CDbCriteria();
    $criteria->select='*';
    $criteria->addInCondition('user_id',$user_id);
    $cur_user=User::model()->findAll($criteria);
    foreach($cur_user as $k=>$v){
        $user_info[$k]['user_id'] = $v->user_id;
        $user_info[$k]['phone'] = $v->user_name;
        $user_info[$k]['rid'] = isset($param['rid']) ? $param['rid'] : 0;
        $user_info[$k]['id'] = $param['id'];
        $user_info[$k]['sequence_id'] = $v->sequence_id;
        $sms = SmsCrontabConfig::model()->find('id=:id and status=1', array('id' => $param['id']));
        $sms->uptime = time();
        $sms->save();
        self::SendReward($user_info, $param);
    }

}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42261次
    • 积分:1163
    • 等级:
    • 排名:千里之外
    • 原创:55篇
    • 转载:145篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论