按值PHP合并数组

时间:2017-04-10 10:36:44

标签: php arrays

我有问题,我想按值合并数组。下面是一个条目示例,条目数组有100条记录


Array
(
    [0] => Array
        (
            [id] => 1
            [code] => dfrr5tv5t5vt5
            [status] => online
        )

    [1] => Array
        (
            [id] => 2
            [code] => e32e3e2e2323e23e
            [status] => online
        )

    [2] => Array
        (
            [id] => 1
            [desc] => Some_description
        )

    [3] => Array
        (
            [id] => 2
            [desc] => Some_description_2
        )
    ....
)

我想通过[id]

通过合并数组获得以下结果

Array
(
    [0] => Array
        (
            [id] => 1
            [code] => dfrr5tv5t5vt5
            [status] => online
            [desc] => Some_description
        )

    [1] => Array
        (
            [id] => 2
            [code] => e32e3e2e2323e23e
            [status] => online
            [desc] => Some_description_2
        )

    ....
)

1 个答案:

答案 0 :(得分:0)

使用关联数组。使用$row["id"]作为关联索引。

$result = [];
foreach ($arr as $row) {
    $result[$row["id"]] = isset($result[$row["id"]]) ? array_merge($result[$row["id"]], $row) : $row;
}
$result = array_values($result); // optional, this removes associative keys