将数组与对象合并-根据键更新重复项并添加唯一

时间:2018-09-04 11:43:40

标签: php arrays

我有2个数组,其中包含对象。 我正在寻找合并数组并更新或添加对象到合并数组的方法。

如果要更新对象,则需要使用匹配的对象增加一个值。

这是我需要的数据和结果的示例。

数组1:

[
    {
        "user": "user1",
        "time": 8600
    },
    {
        "user": "user2",
        "time": 8600
    }
]

数组2:

[
    {
        "user": "user1",
        "time": 5400
    },
    {
        "user": "user3",
        "time": 5400
    }
]

需要将这两个数组转换为:

[
    {
        "user": "user1",
        "time": 14000
    },
    {
        "user": "user2",
        "time": 8600
    },
    {
        "user": "user 3",
        "time": 5400
    }
]

您将看到user 1已更新。 user 1的时间值已加在一起(8600 + 5400) 并且user 3已作为新对象添加到数组。

我尝试遍历一个数组并为每个对象进行测试,但是未成功获得所需的结果。 我看过类似array_merge_recursive之类的东西,但我认为这不会满足我的需求。

这是我尝试过的代码

$newArray = array();

foreach ($array1 as $user) {
    $array1User = $user->user;
    $array1Time = $user->time;

    foreach ($array2 as $user2) {
        $array2User = $user2->user;
        $array2Time = $user2->time;

        // If the user already exists
        if ($array1User == $key => $array2User) {
            // Update item
            $newArray[$key]->time = $array1Time + $array2Time;
        }
        else {
            // Add item
            $newObj = new stdClass();
            $newObj->user = $newAttendeeEmail;
            $newObj->time = $newAttendeeTime;

            // Add new attendee to event details
            $newArray[] = $newObj;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这应该为您解决问题,结果将是$array1,其中包含所有用户和累积的时间。

  

我必须更改2个数组的JSON字符串以使它们成为有效的JSON,所以请注意,如果JSON字符串实际上包含单引号的变量名和值,因为这是无效的JSON

<?php 

$json1 = '[
    {
        "user": "user1",
        "time": 8600
    },
    {
        "user": "user2",
        "time": 8600
    }
]';
$json2 = '[
    {
        "user": "user1",
        "time": 5400
    },
    {
        "user": "user3",
        "time": 5400
    }
]';

$array1 = json_decode($json1);
$array2 = json_decode($json2);

foreach ($array1 as $one) {
    $found = false;
    foreach ($array2 as $two ) {
        // does array 2 contain a user not in array1
        if ( $one->user == $two->user) {
            $one->time += $two->time;
            $found = true;
            break;   
        }
    }   
    // cannot of found this user in $two so add it to $one
    if ( ! $found ) {
        $array1[] = $two;
    }
}

print_r($array1);

结果

Array
(
    [0] => stdClass Object
        (
            [user] => user1
            [time] => 14000
        )

    [1] => stdClass Object
        (
            [user] => user2
            [time] => 8600
        )

    [2] => stdClass Object
        (
            [user] => user3
            [time] => 5400
        )

)