帮助合并2个数组并按键排序

时间:2009-03-26 19:17:54

标签: php arrays multidimensional-array

我在基本的php问题上遇到了一些麻烦,想知道是否有人可以帮助我。基本上我需要结合2个查询的结果,并根据键合并数组,同时将1个键保留为两个查询中存在的1个值。

例如:“select * from table 1,table 2 where table1.id = table2.id”...制作一个数组。

然后:“select * from table3,table4 where table3.id2 = table4.id2”..制作另一个数组。

最后:while($ res){打印每一行}。

有关如何处理此问题的任何想法?伪代码非常感谢。 id之间的关系是table1.id = table3.id,但其他id只是在查询中显示的表之间进行连接。

2 个答案:

答案 0 :(得分:3)

<?php

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

// Sort by key
ksort($new_array);

?>

答案 1 :(得分:2)

如果你不需要单独使用2个数组,我会在SQL中使用union,它应该更快,更少开销。

例如:

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

这确实假设两个阵列具有相同的结构。 mySQL但语法是标准SQL而不是mySQL特定。

或:

"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"