Search code examples
phparraysmergegrouping

Merge arrays of associative arrays by shared column values


I want to merge two arrays based on a common column value. Here are my 2 arrays:

$array1 = [
    [
        "total_process_per_category" => "6",
        "category_id" => "1"
    ],
    [
        "total_process_per_category" => "2",
        "category_id" => "2"
    ]
];

$array2 = [
    [
        "total_pinned_per_category" => "16",
        "category_id" => "1"
    ],
    [
        "total_pinned_per_category" => "4",
        "category_id" => "2"
    ]
];

I want to merge these arrays to get:

array (
  0 => 
  array (
    'total_process_per_category' => '6',
    'total_pinned_per_category' => '16',
    'category_id' => '1',
  ),
  1 => 
  array (
    'total_process_per_category' => '2',
    'total_pinned_per_category' => '4',
    'category_id' => '2',
  ),
)

As you can see, the two arrays have the same key ['category_id'] and same value as well.

I want to make a result where ['total_process_per_category'] and ['total_pinned_per_category'] are placed together on the same array based on their ['category_id'] value.

I got this using a nested foreach, but it looks so ugly. Please show me a better way.


Solution

  • you can try array_reduce:

    $someVariable = 'someValue';
    $result = array_reduce(array_merge($array1, $array2), function ($carry, $item) use ($someVariable) {
        if (isset($carry[$item['category_id']])) {
            $carry[$item['category_id']] = array_merge($carry[$item['category_id']], $item);
        } else {
            $carry[$item['category_id']] = $item;
        }
        return $carry;
    }, array());
    
    var_dump($result);