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

时间:2022-03-23 07:37:44

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.

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

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

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

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

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

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

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

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.

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

2 个解决方案

#1


<?php

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

// Sort by key
ksort($new_array);

?>

#2


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

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

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.

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

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"

#1


<?php

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

// Sort by key
ksort($new_array);

?>

#2


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

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

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.

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

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"