本文實例講述了Yii遍歷行下每列數據的方法。分享給大家供大家參考,具體如下:
效果圖如下:
控制器(1種):
//顯示列表 public function actionList() { //實例化對象 $model= new Qiu(); $country = \Yii::$app->db; //查詢數據 $data = $country->createCommand("select * from qiu join region on qiu.region_id=region.region_id")->queryAll(); $region_ids = $country->createCommand("select region_id from region")->queryAll(); $region = $country->createCommand("select * from region")->queryAll(); //遍歷數組 $ids = array(); $names = array(); $count = array(); //遍歷區域ID foreach ($region_ids as $key => $v) { $ids[$key] = $v['region_id']; } //print_r($ids);die; //遍歷球隊 foreach ($ids as $key => $val) { $data =Qiu::find()->where(['region_id'=>$val])->asArray()->all(); $count[]=count($data); $rows[$val] = $data; } //print_r($rows);die; //根據所有記錄進行遍歷,顯示最多行數 $ji = max($count); $arr = array(); //找出對應的球隊 for($i=0;$i<$ji;$i++) { foreach($rows as $key => $val) { if(isset($val[$i])) { $arr[$i][$key] = $val[$i]['q_name']; } else { $arr[$i][$key] = ''; } } } //var_dump($arr);die; //分配數據 return $this->render('list',['arr'=>$arr,'region'=>$region]); }
(2種):
public function actionList1() { //實例化模型層 $region = new Region; $qiu = new Qiu; //取出區域表的iQiud和所有數據,隊表數據 $region_ids = $region->find()->select('region_id')->column(); $areas = $region->find()->asArray()->all(); $team = $qiu->find()->asArray()->all(); $count = array(); $info = array(); foreach ($region_ids as $aid) {//1,2,3--6 foreach ($team as $key=>$val) { if($val['region_id'] == $aid){ $info[$aid][] = $val; $count[]=count($info[$aid]); } } } //var_dump($count);die; $con = max($count); $arr = array(); for ($i=0; $i <$con ; $i++) { foreach ($info as $key => $val) { if(isset($val[$i])){ $arr[$i][$key] = $val[$i]['q_name']; } else { $arr[$i][$key] = ''; } } } //var_dump($arr);die; return $this->render('list',['arr'=>$arr,'region'=>$areas]); }
視圖層:
<table border="1"> <!--一行區域--> <tr > <?php foreach ($region as $key => $v1) {?> <td><?php echo $v1['region_name']; ?></td> <?php }?> </tr> <!--每列球隊--> <?php foreach ($arr as $key => $val) {?> <tr> <?php foreach ($val as $key => $v) {?> <td><?php echo $v; ?></td> <?php } ?> </tr> <?php } ?> </table>
更多關於Yii相關內容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基於Yii框架的PHP程序設計有所幫助。