简体   繁体   English

PHP:合并两个对象数组

[英]PHP: Merge two array of objects

Array 1: 阵列1:

array (size=1)
   0 => 
      object(stdClass)[93]
         public 'case' => string '12571' (length=5)
         public 'status' => string 'aktiv' (length=5)
         public 'id' => string '001345821' (length=9)
         public 'expires' => string '1392681600' (length=10)

Array 2: 阵列2:

array (size=66)
   0 => 
     object(stdClass)[25]
       public 'id' => string '001345821' (length=9)
       public 'date' => int 1415602800
       public 'amount' => string '1069.31' (length=7)
   1 => 
     object(stdClass)[26]
       public 'id' => string '001345680' (length=9)
       public 'date' => int 1415602800
       public 'amount' => string '1035.00' (length=7)

I want to merge array 1 and 2 on the "id" field and only keeping matches from array 1. 我想在“ id”字段上合并数组1和2,只保留数组1的匹配项。

What i want: 我想要的是:

array ()
   0 =>
     object(stdClass)
       public 'case' => string '1257' (length=5)
       public 'status' => string 'aktiv' (length=5)
       public 'id' => string '001345821' (length=9)
       public 'expires' => string '1392681600' (length=10)
       public 'date' => int 1415602800
       public 'amount' => string '1069.31' (length=7)

If your object contains only properties, you could use array merge in this case. 如果对象仅包含属性,则在这种情况下可以使用数组合并。 Of course, first up, just use a loop. 当然,首先,只需使用循环即可。 Then under the loop, make your if checking for those who share the same ids then you need to cast them as array them merge, then recast them as object again: 然后在循环下, if检查共享相同ID的对象,则需要将它们强制转换为它们合并的数组,然后再次将它们重铸为对象:

foreach($array2 as &$value2) {
    foreach($array1 as $value1) {
        if($value2->id == $value1->id) {
            $value2 = (object) array_merge((array) $value2, (array) $value1);
        }
    }
}

Sample Out 取样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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