Array merge on key of two associative arrays in php?

冷暖自知 提交于 2019-12-18 13:38:32

问题


How can I merge these two array together?

Array
(
[0] => Array
    (
        [id] => 5
        [cnt] => 14
    )

[1] => Array
    (
        [id] => 8
        [cnt] => 2
    )

)

Array
(
    [0] => Array
        (
            [id] => 8
            [binding] => hardcover
        )

    [1] => Array
        (
            [id] => 5
            [binding] => softcover
        )
)

The expected result is:

Array
    (
        [0] => Array
            (
                [id] => 5
                [binding] => softcover
                [cnt] => 14
            )

        [1] => Array
            (
                [id] => 8
                [binding] => hardcover
                [cnt] => 2
            )

    )

The merge of these two array should happen on the [id] value and not on any sort of the array. How can I do this with php in a fast way?


回答1:


$output = array();

$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
  $id = $value['id'];
  if ( !isset($output[$id]) ) {
    $output[$id] = array();
  }
  $output[$id] = array_merge($output[$id], $value);
}

var_dump($output);

Optionally if you want to reset output's keys, just do:

$output = array_values($output);


来源:https://stackoverflow.com/questions/9112920/array-merge-on-key-of-two-associative-arrays-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!