使用codeigniter php在数组中推送数据

时间:2016-01-07 13:45:04

标签: php codeigniter

我有user_sport_tbl,sport_tbl表。在user_sport_tbl我有sport_id但没有运动名称。运动名称在sport_tbl。

我有一个模型的getUserSport()函数。

我的查询: -

$query = $this->db->get_where('user_sport_tbl',array('username' => $username));

我希望sport_name为每个sport_id,并希望将sport_name合并到数组中。

我的代码: -

    public function getUserSport()
{
    $username = $this->session->userdata('username');
    $query = $this->db->get_where('user_sport_tbl',array('username' => $username));
    if($query->num_rows > 0)
    {
        foreach($query->result() as $item)
        {
            $query1 = $this->db->query("select sport_name from sport_tbl where sport_id=$item->sport_name order by sport_id limit 1");
            $sql1 = $query1->row();

            $data[] = array_push($item, $sql1->sport_name);
        }
        return $data;
    }
}

我目前的退货数据: -

 [user_match_id] => 7 [sport_id] => 2 [match_id] => 3 [username] => admin

我想添加[sport_name] =>板球。

我想返回一个带有sportname

的数组

2 个答案:

答案 0 :(得分:0)

尝试此编码

public function getUserSport()
{
   $data = array();
    $username = $this->session->userdata('username');
    $query = $this->db->get_where('user_sport_tbl',array('username' => $username));
    if($query->num_rows > 0)
    {
        foreach($query->result() as $key=>$item)
        {
            $query1 = $this->db->query("select sport_name from sport_tbl where sport_id=$item->sport_name order by sport_id limit 1");
            $sql1 = $query1->row();

            $item[$key]['sport_name']  = $sql1->sport_name;

            $data[] = $item;
        }
        return $data;
    }
}

答案 1 :(得分:0)

试试这个

public function getUserSport()
{
    $username = $this->session->userdata('username');
    $query = $this->db->get_where('user_sport_tbl',array('username' => $username));
    if(empty($query))
    {
        foreach($query->result_array() as $item)
        {
            $sportsId = $item[0]['sport_name'];
            $query1 = $this->db->query("SELECT sport_name FROM sport_tbl WHERE sport_id = $sportsId ORDER BY sport_id LIMIT 1");
            $result = $query1->result_array();

            $data[] = array_push($item, $result[0]['sport_name']);
        }
        return $data;
    }
}

或者也可以使用连接查询 (未经过测试。如果有任何错误修复它。  或发布消息她)

public function getUserSport()
{
    $username = $this->session->userdata('username');
    $query = $this->db->query(
        "SELECT user_sport_tbl.sport_name, sport_tbl.sport_name
        FROM user_sport_tbl 
        INNER JOIN sport_tbl 
        ON user_sport_tbl.username = sport_tbl.sport_name
        WHERE user_sport_tbl.username = '$username' ORDER BY sport_tbl.sport_id LIMIT 1");
    $result = $query->result_array();

    return $data;
}