tp5 隨機獲取商品

  /**
     * 隨機獲取商品
     */
    public function getRandGoods(){
     
        $map['status'] = 1; //狀態;上架
        $map['num'] = ['>','0'];//庫存
        $query = model('goods');
        $about = $query
            ->where($map)
            ->count();
        $limit = 20;       //抽取數量
        $toffset=range(0,$about);
        shuffle($toffset);
        if($toffset){
            $st = $toffset[0];     //隨機第幾個開始
            $lens = $about - $st ; //個數是否足夠
            if($lens < $limit){
                $st = $limit - $lens;
            }
            if($st <=0 || $st <= $limit){
                $st = 0;
            }
        }
        unset($map);
        $map['g.status'] = 1; //狀態;上架
        $map['g.num'] = ['>','0'];//庫存
        $l_list = $query    //獲取需要隨機條件的數組
            ->alias('g')
            ->where($map)
            ->order('g.recommend desc,g.addtime desc,g.virtual_sales desc')
            ->join('shop s','s.id = g.shop_id')
            ->field('g.*,s.district_name')
            ->limit($st,$limit)
            ->select();
        $len = count($l_list); //統計符合條件的數組個數
        $len = $len-1;
        $arr=range(0,$len);
        shuffle($arr);//模擬數組,隨機下標

        $look_list =array();
        foreach($arr as $values)
        {
            $look_list[] = $l_list[$values];
            if(count($look_list) == 10){   //獲得數量
                break;
            }
        }
        \Org\Response::show(200,'access!', $look_list);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章