【问题标题】:merge two multidimensional array based on same ID合并两个基于相同ID的多维数组
【发布时间】:2016-08-18 10:24:14
【问题描述】:

在合并基于相同 ID 的两个多维数组时,我遇到了一个问题。

在下面的示例中,我创建了两个数组 - Array1Array2。两个数组都包含具有ID 属性的对象。基于ID属性,数组应该被合并并得到结果数组:

数组1

Array
(
 [0] => stdClass Object
    (
        [claimtotal] => 
        [total] => 4
        [ID] => 3

    )

[1] => stdClass Object
    (
        [claimtotal] => 20
        [total] => 1
        [ID] => 4
    )
)

数组2

Array
(
 [0] => stdClass Object
    (
        [ID] =>2 
        [name] => test1

    )

[1] => stdClass Object
    (
        [ID] => 3
        [name] => test2
    )
[2] => stdClass Object
    (
        [ID] =>4 
        [name] => test3
    )

[3] => stdClass Object
    (
        [ID] => 5
        [name] => test4
    )
)

结果数组

Array
(
 [0] => stdClass Object
    (
        [ID] =>2 
        [name] => test1
        [claimtotal] => 
        [total] => 
    )

[1] => stdClass Object
    (
        [ID] => 3
        [name] => test2
        [claimtotal] => 
        [total] => 4
    )
[2] => stdClass Object
    (
        [ID] =>4 
        [name] => test3
        [claimtotal] => 20
        [total] => 1
    )

[3] => stdClass Object
    (
        [ID] => 5
        [name] => test4
        [claimtotal] => 
        [total] => 
    )
)

我怎样才能做到这一点?

【问题讨论】:

  • 请向我们展示您为获得所需结果所做的尝试

标签: php multidimensional-array


【解决方案1】:

如果这些是没有方法的简单对象:

foreach($firstArray as $key => $firstObject){
foreach($secondArray as $secondObject){
    if($firstObject['id'] === $secondObject['id']){
        $firstArray[$key] = (object) array_merge((array) $firstObject, (array) $secondObject);
    }               
  }
}

看起来很凌乱,但在没有引入另一个循环来遍历对象属性的情况下完成了这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-13
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2013-09-26
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多