search

Home  >  Q&A  >  body text

Merge associative arrays with shared column values

I want to merge two arrays based on common column values. 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, both arrays have the same key ['category_id'] and the same value.

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

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

P粉966979765P粉966979765401 days ago613

reply all(2)I'll reply

  • P粉366946380

    P粉3669463802023-11-10 00:52:21

    This can be done without "ugly nested foreach". Merge the two arrays before iterating, grouping by category_id value. After the loop ends, use array_values() to clear the temporary first-level keys.

    Code: (Demo) (array_reduce() version)

    $result = [];
    foreach (array_merge($array1, $array2) as $row) {
        $result[$row['category_id']] = ($result[$row['category_id']] ?? []) + $row;
    }
    var_export(array_values($result));

    Output:

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

    reply
    0
  • P粉071743732

    P粉0717437322023-11-10 00:45:48

    You can tryarray_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);

    reply
    0
  • Cancelreply