使用codeigniter php在数组的每个索引中推送数组数据

时间:2016-01-08 04:10:20

标签: php codeigniter

我有两张表sport_tblmatch_tbl。在sport_tbl中,我定义了sport_name,例如板球。在match_tbl中,我有match_namematch_datesport_id

我想显示每个sport_name的match_date(例如,我正在显示板球运动的match_date列表,我想显示每个日期都有match_name列表)。

我想展示一个不同的match_date

图像 enter image description here

我的控制器代码: -

        $url = 'cricket' // for example first sport_name
    $data['getSportMatch'] = $this->user_model->getSportMatch($url);

我的型号代码: -

    public function getSportMatch($sport)
{
    $query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
    if($query->num_rows > 0)
    {
        foreach($query->result() as $item){
            $data[] = $item;
        }
        return $data;
    }
}

我的代码在视图中: -

<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>

match_date))?&gt;这里我要显示每个match_date的列表match_name

我的表格结构图片

1)sport_tbl

Sport_tbl

2)match_tbl

match_tbl

3)另一个match_tbl

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个编码...

  public function getSportMatch($sport)
{
    $query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON  st.sport_id =  mt.sport_id WHERE st.sport_name ='".$sport."'");
    if($query->num_rows > 0)
    {
       $query_result = $query->result_array();

       $final_result = array();

       foreach($query_result as $result ) {

       $date =  $result['match_date'];

       $final_result[$date][] = $result;

       }

       return $final_result;

    }
}

查看编码: -

 if(isset($final_result)) {

        foreach($final_result as $result) {

        echo $result['match_date']; //  First display match date

  if(isset($result['match_date'])) {
            foreach($result['match_date'] as $match) {

                echo $match['match_name']; // Second listout the match name 

            }
    }
        }

    }

答案 1 :(得分:0)

你可以轻松地在模型中解决这个问题。如果我不明白错。你需要2个模型功能。 1.将得到运动名称 2.将获得给定运动名称的匹配

//model functions

function get_sports(){
    $data = array();
   $sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
      if($sports)
       {
        foreach($sports as $sport){

            $data[$sport->sport_name] = $this->get_matches($sport->sport_name);
        }
        return $data;
       }

}


function get_matches($sport_name){
    $matches =   $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
    return $matches;

}

所以在视图中数据将是这样的

$data => array(
    'cricket'=> array(0 => array(
                                  'match_id' => 11,
                                   'sport_id' = 2 .....

)))