Denny Kurniawan
Denny Kurniawan

Reputation: 1905

How can i merge multiple result from multiple query in single json

i so intersted how i can merge result from two query in single json file?

i have one query : Select * from student

and my second query : select * from teacher

$result = array_merge($query1, $query2);
echo json_encode($result);

i have use array_merge but it not work, how can i fix this. Thanks for your help

Upvotes: 1

Views: 1370

Answers (4)

JYoThI
JYoThI

Reputation: 12085

As per your comment you have relationship between two tables so you just use single query to get merged result like this .

JUST use mysql JOIN

select * from student join teacher on student.teacher_id = teacher.id ;

on condition should be changed as your need with your relatioship columns

Upvotes: 1

Rahmatullah Darwish
Rahmatullah Darwish

Reputation: 5

First, change your query result to an array then merge both.

Upvotes: 0

Sloan Thrasher
Sloan Thrasher

Reputation: 5040

If the columns are different in the two tables, you an create an array with two elements, the first containing the results of the student query, and the second containing the results of the teacher query.

$results = array(
    'students' => $student_results,
    'teachers' => $teacher_results
)

If the two tables are related, IOW, there is a foreign key in one pointing to a record in the other, you would use one query that joins the two tables.

Upvotes: 0

Jeffrey Hitosis
Jeffrey Hitosis

Reputation: 325

If your tables have same column count you can use UNION ALL in your query.

Select * from student
UNION ALL
select * from teacher

Upvotes: 0

Related Questions