3v4l.org

run code in 300+ PHP versions simultaneously
<?php $input_array = [ ['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 1'], ['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 2'], ['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 3'], ['id' => 3, 'name' => 'ProductName2', 'comment' => 'best product comment 4'], ['id' => 3, 'name' => 'ProductName2', 'comment' => 'best product comment 5'] ]; $output_array = array_values(array_reduce($input_array, function($output_array, $item) { if (array_key_exists($item['id'], $output_array)) $output_array[$item['id']]['comment'][] = $item['comment']; else { $item['comment'] = (array)$item['comment']; $output_array[$item['id']] = $item; } return $output_array; }, [])); var_dump($output_array);

preferences:
25.81 ms | 406 KiB | 5 Q