根据特定值合并两个 php 对象或数组
Merging two php objects or arrays on specific value
我在 PHP 中合并两个对象时遇到问题,因为只有当特定键上的特定值匹配时我才需要合并它们。
Table 1 位用户:
id | name | email | ....
1 | first | some@ | ....
这个 table 有更多数据,但我认为这对这个问题不重要。
table 2 个服务:
id | userID | phone | ....
1 |1 | 12345
table 看起来非常丑陋,所以我将展示结果的样子:
array(3) {
[0]=> object(stdClass)#227 (5) {
["id"]=> string(1) "1"
["name"]=> string(4) "rade"
["email"]=> string(13) "mail@mail.com"
...
第二个:
array(3) {
[0]=> object(stdClass)#8 (24) {
["ID"]=> string(2) "20"
["userID"]=> string(1) "1"
["phone"]=> string(4) "6541"
我在两个数组中可能没有相同数量的结果,第一个可能并且将会有更多,并且当第一个的 id 与第二个的 userID 匹配时我需要合并它们。我已经通过嵌套两个 foreach 循环来完成此操作,但我讨厌这种方式,当数据库每个都有 1000 个时,它将是 100 万个循环。
foreach($objONE as $one) {
foreach($objTWO as $two) {
if($two->userID == $one->id) {
$name = $one->name;
$phone = $two->phone;
//and i use all data
}
}
}
我直接使用结果,所以不需要将它们作为对象保存,它们可以转换为数组。有什么解决办法吗?
感谢 Wazelin and nerdlyist I was looking at this problem wrong way, this was SQL not PHP problem, I just edited mine query and I got results that I need, and once again thanks Wazelin 为我指明了正确的方向,左连接做得很好,生病的 post 代码让有类似问题的人可以更快地找到解决方案 ;)
SELECT * FROM users LEFT JOIN service ON users.id=service.userID WHERE users.grupa = 'service'
我在 PHP 中合并两个对象时遇到问题,因为只有当特定键上的特定值匹配时我才需要合并它们。
Table 1 位用户:
id | name | email | ....
1 | first | some@ | ....
这个 table 有更多数据,但我认为这对这个问题不重要。
table 2 个服务:
id | userID | phone | ....
1 |1 | 12345
table 看起来非常丑陋,所以我将展示结果的样子:
array(3) {
[0]=> object(stdClass)#227 (5) {
["id"]=> string(1) "1"
["name"]=> string(4) "rade"
["email"]=> string(13) "mail@mail.com"
...
第二个:
array(3) {
[0]=> object(stdClass)#8 (24) {
["ID"]=> string(2) "20"
["userID"]=> string(1) "1"
["phone"]=> string(4) "6541"
我在两个数组中可能没有相同数量的结果,第一个可能并且将会有更多,并且当第一个的 id 与第二个的 userID 匹配时我需要合并它们。我已经通过嵌套两个 foreach 循环来完成此操作,但我讨厌这种方式,当数据库每个都有 1000 个时,它将是 100 万个循环。
foreach($objONE as $one) {
foreach($objTWO as $two) {
if($two->userID == $one->id) {
$name = $one->name;
$phone = $two->phone;
//and i use all data
}
}
}
我直接使用结果,所以不需要将它们作为对象保存,它们可以转换为数组。有什么解决办法吗?
感谢 Wazelin and nerdlyist I was looking at this problem wrong way, this was SQL not PHP problem, I just edited mine query and I got results that I need, and once again thanks Wazelin 为我指明了正确的方向,左连接做得很好,生病的 post 代码让有类似问题的人可以更快地找到解决方案 ;)
SELECT * FROM users LEFT JOIN service ON users.id=service.userID WHERE users.grupa = 'service'