简体   繁体   中英

Merging arrays of objects within another array with PHP

I have an array of arrays, with each "internal" array holding any number of objects. While no objects within its parent array can be duplicated, within the "outer" array holding all of the arrays, duplicates can occur. My goal is to merge all of the internal arrays so that there is just one array with no duplicates.

So far, I have tried using array_merge and array_merge_recursive while looping through the outer array, but that has not been successful. I'm not sure if I'm explaining this very clearly, but is this something that can be done?

Here's a var_dump as an example of the initial array:

array (size=4)
    27 => 
        array (size=4)
            0 => 
                 object(stdClass)[75]
                 public 'subTestId' => string '1' (length=1)
                 public 'testMakerTestId' => null
            1 => 
                 object(stdClass)[76]
                 public 'testMakerTestId' => string '5844' (length=4) 
            2 => 
                 object(stdClass)[77]
                 public 'subTestId' => string '23' (length=2)
            3 => 
                 object(stdClass)[78]
                 public 'subTestId' => string '12' (length=2)
    24 => 
        array (size=3)
            0 => 
                object(stdClass)[79]
                public 'subTestId' => null
            1 => 
                object(stdClass)[80]
                public 'subTestId' => null
            2 => 
                object(stdClass)[81]
                public 'subTestId' => string '12' (length=2)
    1 => 
        array (size=1)
            0 => 
                object(stdClass)[82]
                public 'subTestId' => string '23' (length=2)
    25 => 
         array (size=1)
             0 => 
                 object(stdClass)[83]
                 public 'subTestId' => string '23' (length=2)

I want to merge them all and not have any duplicates of the "subTestId" field. What would be the best way to go about this? Any help is greatly appreciated.

Thanks!

I haven't tested this but I think it should work:

$merged = [];
foreach ($outer as $inner) {
  foreach ($inner as $obj) {
    $id = $obj->subTestId;
    if(!array_key_exists($id, $merged)) {
      $merged[$id] = $obj;
    }
  }
}

It will store each object from each of the inner arrays in $merged using its subTestID as the key but only if that key is not already in $merged .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM