Merging arrays based on a value of the key

前端 未结 9 1325
予麋鹿
予麋鹿 2020-12-19 09:03

I have two arrays of arrays that have an id key, and I\'d like to merge the data together based on that array\'s key and key value. The data would look somethin

9条回答
  •  心在旅途
    2020-12-19 09:50

    Pure php solution is to use array_replace_recursive like this:

    array_replace_recursive(
      array_combine(array_column($color, "id"), $color),
      array_combine(array_column($size, "id"), $size)
    );
    

    You should notice that array_replace_recursive merge arrays by keys. So, if you get such data from database:

    $color = [
        ['id' => 1, 'color' => 'red'],
        ['id' => 2, 'color' => 'red']
    ];
    
    $size = [
        ['id' => 2, 'size' => 'SM']
    ];
    

    array_replace_recursive will return corrupted merge:

    $combined = [
        ['id' => 2, 'color' => 'red', 'size' => 'SM'],
        ['id' => 2, 'color' => 'red']
    ];
    

    The solution is to combine array_replace_recursive with array_column and array_combine for merging arrays by their's id field:

    array_replace_recursive(
      array_combine(array_column($color, "id"), $color),
      array_combine(array_column($size, "id"), $size)
    );
    

    array_combine(array_column($color, "id"), $color) creates associative array with id as keys.

    So, in your case it will return:

    $combined = [
        1 => ['id' => 1, 'color' => 'red', 'size' => 'SM'],
        2 => ['id' => 2, 'color' => 'green', 'size' => 'XL'],
        3 => ['id' => 3, 'color' => 'blue', 'size' => 'MD'],
        4 => ['id' => 4, 'size' => 'LG'],
    ];
    

提交回复
热议问题