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.
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)
Output:
You can try
array_reduce
: