3v4l.org

run code in 300+ PHP versions simultaneously
<?php $a = Array(0 => Array('member_id' => 6, 'total' => 1, 'sorting' => 0), 1 => Array('member_id' => 7, 'total' => 2, 'sorting' => 1) ); $b = Array(0 => Array('member_id' => 2, 'total' => 3), 1 => Array('member_id' => 6, 'total' => 1), 2 => Array('member_id' => 7, 'total' => 2) ); /* * first, store all records with matching member_id */ $c = []; foreach ($b as $key0 => $value0) { foreach ($a as $key1 => $value1) { // matching 'member_id'? if ($value0['member_id'] === $value1['member_id']) { // inject record into store $c $c[] = $a[$key1]; } } } /* * second, inject non-matching records from $b into store $c */ $ids = array_column($c, 'member_id'); foreach ($b as $key => $value) { if (!in_array($value['member_id'], $ids)) { $sorting = max(array_column($c, 'sorting')) + 1; $value['sorting'] = $sorting; $c[] = $value; } } echo '<pre>'; print_r($c); echo '</pre>';
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.27, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
<pre>Array ( [0] => Array ( [member_id] => 6 [total] => 1 [sorting] => 0 ) [1] => Array ( [member_id] => 7 [total] => 2 [sorting] => 1 ) [2] => Array ( [member_id] => 2 [total] => 3 [sorting] => 2 ) ) </pre>

preferences:
127.92 ms | 408 KiB | 5 Q