第一次摸tp5的时候分页做的的确挺头疼,用 paginate 得到的数据直接用foreach会报错,后来选择了php转数组方法放到common里面用了好久,偶然看手册发现还有一个 toArray 属性,瞬间想给不认真看手册的自己一拳。
手册数据转换传送门:https://www.kancloud.cn/manual/thinkphp5/138667
demo:
public function demo(){
$member_id = Session::get("member_id");
$where['member_id'] = $member_id;
$quan_list = Db::name('member_quan')->where($where)->order("create_time desc")->paginate(10);
$page = $quan_list->render();
$quan_to_array = $quan_list->toArray();
$quan_list_array = $quan_to_array['data'];
if(isset($quan_list_array) && !empty($quan_list_array)){
foreach($quan_list_array as $key=>$item){
//转换成的二维数组可以直接追加元素,用以前台输出
$coupon_id = $item['coupon_id'];
$coupon_info = Db::name("quan_list")->where("id",$coupon_id)->find();
$quan_list_array[$key]['quan_name'] = $coupon_info['quan_name'];
$quan_list_array[$key]['quan_price'] = $coupon_info['quan_price'];
$quan_list_array[$key]['end_time'] = $coupon_info['end_time'];
$quan_list_array[$key]['quan_code'] = $coupon_info['quan_code'];
}
}
$this->assign("quan_list_array",$quan_list_array);
$this->assign("page",$page);
return $this->fetch('member_coupon');
}