1

I Have 2 table that I want to join them and fetch some data like this I have one student with multiple grade

   {
    "student": {
    "studentID": "2",
    "Name": "s1",
    "age": " 12",
    "grade": [
    {
      "GradeID": "2"
    },{
      "GradeID": "3"
    }
]
  }

I fetch this data from two query in a function in my model and then use json_encode in my controller for my output but I have this

{
  "student": {
    "studentID": "2",
    "Name": "s1",
    "age": " 12"
},
    "grade": [
    {
      "GradeID": "2"
    },{
      "GradeID": "3"
    }
]
  }

and now I don't know how to use json_encode for the first format. thanks

my model(student):
 function get_student_id($id)
    {
        $student['student']=
            $this->db->select('tbl_student.*')
                 ->from('tbl_student')
                 ->where('tbl_student.SID',$id)
                 ->get()->row();

        $student['grade']=
            $this->db->select('tbl_grade.GradeID')
                ->from('tbl_grade')
                ->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
                ->where('tbl_student.SID',$id)
                ->get()->result();



        return $student;
}

my controller:

public function get_student_id()
    {

        $id = $input['one'];
        $this->load->model('student');
        $temp=$this->student->get_student_id($id);
        $output= json_encode($temp);

        die($output);

    }
3
  • 1
    where is your CODE ??? Commented Feb 21, 2017 at 6:53
  • can you share your query code. I think single query can do all your task using Jonis Commented Feb 21, 2017 at 6:53
  • Simply use json_encode() function it will return json format data. Commented Feb 21, 2017 at 6:58

1 Answer 1

1

You just have to structure the array you're returning from the model correctly. You're putting everything inside two subarrays called student and grade, which are inside the outer array student. Try this:

my model(student):
 function get_student_id($id)
    {
        $student=
            $this->db->select('tbl_student.*')
                 ->from('tbl_student')
                 ->where('tbl_student.SID',$id)
                 ->get()->row();

        $student['grade']=
            $this->db->select('tbl_grade.GradeID')
                ->from('tbl_grade')
                ->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
                ->where('tbl_student.SID',$id)
                ->get()->result();



        return $student;
}

I'm not totally certain you want to call get->row() on the first query, if that doesn't work try get->row_array()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.