Manish Tiwari Manish Tiwari - 3 months ago 19
PHP Question

push data in an array using codeigniter php

I have user_sport_tbl,sport_tbl tables. in user_sport_tbl i have sport_id but not have sport name.Sport name is in sport_tbl.

i have a function of getUserSport() of Model.

my query :-

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


i want sport_name for every sport_id and want to merge sport_name in array.

my code :-

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;
}
}


my present return data:-

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


i want to add [sport_name] => cricket.

I want to return an array with sportname

Answer

Try this coding

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;
    }
}
Comments