Search code examples
phpmergearray-merge

Merging two php objects or arrays on specific value


I have issue with merge of two objects in PHP as I need to merge them only if specific values on specific keys match.

Table 1 users:

id | name | email | ....

1 | first | some@ | ....

This table have more data but I don't think that's important for this question.

table 2 service:

id | userID | phone | ....

1  |1        | 12345

The tables look super ugly so I'll show how result looks like:

array(3) { 
[0]=> object(stdClass)#227 (5) { 
      ["id"]=> string(1) "1" 
      ["name"]=> string(4) "rade" 
      ["email"]=> string(13) "[email protected]" 
      ...

and second one:

array(3) { 
[0]=> object(stdClass)#8 (24) { 
      ["ID"]=> string(2) "20" 
      ["userID"]=> string(1) "1" 
      ["phone"]=> string(4) "6541" 

I may not have same number of results in both arrays, first one may and will have more, and I need to merge them when id of first one matches userID of second one. I have done this with nesting two foreach loops but I hate that way, when database have 1000 of each it will be 1 mil of loops.

foreach($objONE as $one) {
    foreach($objTWO as $two) {
        if($two->userID == $one->id) {
            $name = $one->name;
            $phone = $two->phone; 
            //and i use all data
        }
    }
}

I use results right away so there is no need to keep them as object, they can be converted to arrays. Any ideas how to solve this?


Solution

  • Thanks 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 for pointing me in right direction, left join did great job, ill post code so someone with similar issue can find solution faster ;)

    SELECT * FROM users LEFT JOIN service ON users.id=service.userID WHERE users.grupa = 'service'