1.封裝方法
~~~
function getRandTable($nums, $tables)
? ? ? ? {
? ? ? ? ? ? $num = $nums;? ? //需要抽取的默認(rèn)條數(shù)
? ? ? ? ? ? $table = $tables;? ? //需要抽取的數(shù)據(jù)表
? ? ? ? ? ? $pk = Db::name($table)->getPK();//獲取主鍵
? ? ? ? ? ? $countcus = Db::name($table)->field($pk)->select();//查詢數(shù)據(jù)
? ? ? ? ? ? $con = '';
? ? ? ? ? ? foreach($countcus as $v=>$val){
? ? ? ? ? ? ? ? $con.= $val[$pk].'|';
? ? ? ? ? ? }
? ? ? ? ? ? $array = explode("|",$con);// 拆分
? ? ? ? ? ? $data = [];
? ? ? ? ? ? foreach ($array as $v){
? ? ? ? ? ? ? ? if (!empty($v)){
? ? ? ? ? ? ? ? ? ? $data[$v]=$v;//循環(huán)健值
? ? ? ? ? ? ? ? };
? ? ? ? ? ? }
? ? ? ? ? ? $a=array_rand($data,$num) ;//隨機(jī)數(shù)組
? ? ? ? ? ? $list = Db::name("$table")->where($pk,'in',$a)->select();
? ? ? ? ? ? return json($list);
? ? ? ? ? ? }
~~~
2.查詢數(shù)據(jù)
~~~
$q =Db::name('cms_testdetail')->where('rand()')->limit(2)->select();
~~~