views:

525

answers:

2

I am having some trouble with a basic php issue and want to know if anyone can help me out. Basically I need to combine the results of 2 queries, and merge the arrays based on the key, while retaining the 1 key to 1 value that is present in both queries.

For example: "select * from table 1, table 2 where table1.id = table2.id"... make an array of this.

Then: "select * from table3, table4 where table3.id2 = table4.id2" .. make another array.

Finally: While ($res) { print out each line with }.

Any ideas on how to handle this? Pseudo code greatly appreciated. The relationship betwee the ids is that table1.id = table3.id but the other ids are just to join between the tables as presented in the queries.

+1  A: 
<?php

// Merge arrays keeping keys
$new_array = array_merge($array1, $array2);

// Sort by key
ksort($new_array);

?>
Seb
+2  A: 

If you don't need the 2 arrays separately, I'd use a union in SQL, which should be faster and less overhead.

eg:

"(select * from table1, table2 where table1.id = table2.id)
     UNION ALL 
 (select * from table3, table4 where table3.id2 = table4.id2)"

This does assume the same structure for both arrays. mySQL but syntax is standard SQL not mySQL specific.

or:

"Select * from ((select table1.id as id, * from table1, table2 where table1.id = table2.id)
       UNION
      (select table3.id as id, * from table3, table4 where table3.id2 = table4.id2)) as t
 ORDER BY t.id"
sfossen