在PHP中将它们的重复值组合成两个数组,并合并值 - 逗号分隔

So I have this 2 arrays. First has one array in it and the other one has two arrays. They are grouped like this as a result.

array(1) {
  [0]=>
  array(9) {
    ["id"]=>
    int(9)
    ["product_group_id"]=>
    int(9)
    ["sold_to"]=>
    int(107824)
    ["value"]=>
    int(19845)
    ["created_at"]=>
    string(19) "2019-01-24 14:48:25"
    ["updated_at"]=>
    string(19) "2019-01-24 14:48:25"
  }
}
array(2) {
  [0]=>
  array(9) {
    ["id"]=>
    int(17)
    ["product_group_id"]=>
    int(8)
    ["sold_to"]=>
    int(126124)
    ["value"]=>
    int(15555)
    ["created_at"]=>
    string(19) "2019-01-24 14:48:25"
    ["updated_at"]=>
    string(19) "2019-01-24 14:48:25"
  }
  [1]=>
  array(9) {
    ["id"]=>
    int(20)
    ["product_group_id"]=>
    int(8)
    ["sold_to"]=>
    int(141877)
    ["value"]=>
    int(10848)
    ["created_at"]=>
    string(19) "2019-01-24 14:48:25"
    ["updated_at"]=>
    string(19) "2019-01-24 14:48:25"
  }
}

I would like to merge the second array in one single array based on the product_group_id like

['id'=> "17,20", 'product_group_id' => "9", 'sold_to'=> "107824,126124"]

try this one: test case bellow

function groupImplode( $key, $array, $glue = ',' ){
    $result = [];
    foreach( $array as $index => $element ){
        if( array_key_exists( $key, $element ) ){
            if( isset( $result[ $element[$key] ] ) ){
                //concat values
                foreach( array_keys( $element ) as $elementKey ){
                    if( $elementKey !== $key )
                        $result[ $element[$key] ][ $elementKey ] .= $glue . $element[$elementKey];
                }
            }else
                $result[ $element[$key] ] = $element;
        }
    }
    return array_values( $result );
}

$myArray = [
    ['id' => 17, 'product_group_id' => 8, 'sold_to' => 126124, 'value' => 15555, 'created_at' => '2019-01-24 14:48:25', 'updated_at' => '2019-01-24 14:48:25' ],
    ['id' => 20, 'product_group_id' => 8, 'sold_to' => 141877, 'value' => 10848, 'created_at' => '2019-01-24 14:48:25', 'updated_at' => '2019-01-24 14:48:25' ],
];

$res = groupImplode( 'product_group_id', $myArray );
print_r($res);

Build an associative array on the on "product_group_id" then use array_values to reset the keys.

foreach($arr as $sub){
    foreach($sub as $item){
        $new[$item["product_group_id"]][] = $item;
    }
}
$new = array_values($new);