thinkphp5.0 使用paginate 分页后 foreach 循环体内不能处理数据的解决办法

方法一、使用toArray()将查询出来的分页数据转成数组
$data = $goods_list->toArray();

方法二、 $data = $goods_list->all();

替换处理

<?php
//model里面的分页函数
public function pageQuery(){    
    $rs = $this->where($where)->field(true)->order('id desc')->paginate()
    ->each(function($item, $key){
        if($item['status']==1){
            $item['name1'] = $item['name2'];
        }
        $item['imgSize'] = round($item['imgSize']/1024/1024,2);
        return $item;
    });
    return $rs;
}
?>

  

如果each里面涉及到别的表,则代码如下:

<?php
//model里面的分页函数
public function pageQuery(){    
    $rs = $this->where($where)->field(true)->order('id desc')->paginate()   
    ->each(function($item, $key){
        $urs = Db::name('u')->where('isShow',1)->select();
        foreach ($urs as $rkey=>$rv){
            if($item['userScore']>=$rv['startScore'] && $item['userScore']<$rv['endScore']){
               $item['userRank'] = $rv['rankName'];
            }
        }
        return $item;
    });
    return $rs;
}
?>

  

如果each里面涉及到外部参数,则代码如下:

<?php
//model里面的分页函数
public function pageQuery(){
//从别的表获得参数值,一次获取,each中可以重复使用
$urs = Db::name('u')->where('isShow',1)->select(); 
$rs = $this->where($where)->field(true)->order('id desc')->paginate() 
->each(function($item, $key) use ($urs){ 
//使用外部传来的参数$urs
foreach ($urs as $rkey=>$rv){
if($item['userScore']>=$rv['startScore'] && $item['userScore']<$rv['endScore']){
$item['userRank'] = $rv['rankName'];
}
}
return $item;
});
return $rs;
}
?>

  

原文地址:https://www.cnblogs.com/lezuw/p/12553228.html