How to store column data as comma separated values when finding duplicate values in another column?

前端 未结 1 1600
小鲜肉
小鲜肉 2021-01-29 00:49

I must combine or implode subarray values if the product will be the same for any company.

Expected output should be like:

0 => 
array (
    \'compa         


        
相关标签:
1条回答
  • 2021-01-29 01:19

    implode() is not going to be part of a simple/direct solution. You should assign temporary keys using the product values so that you can determine, during each iteration, if you are dealing with the first occurrence (store the whole subarray) or a subsequent occurrence of a product (append/concatenate the new company value using a comma as glue).

    When finished iterating, re-index the array with array_values().

    Code: Demo

    $array = array (
        0 => 
        array (
            'company' => 1,
            'product' => 5,
        ),
        1 => 
        array (
            'company' => 2,
            'product' => 4,
        ),
        2 => 
        array (
            'company' => 6,
            'product' => 5,
        ),
        3 => 
        array (
            'company' => 2,
            'product' => 3,
        ),
    );
    
    foreach ($array as $set) {
        if (!isset($result[$set['product']])) {
            $result[$set['product']] = $set;
        } else {
            $result[$set['product']]['company'] .= ",{$set['company']}";
        }
    }
    var_export(array_values($result));
    

    Output:

    array (
      0 => 
      array (
        'company' => '1,6',
        'product' => 5,
      ),
      1 => 
      array (
        'company' => 2,
        'product' => 4,
      ),
      2 => 
      array (
        'company' => 2,
        'product' => 3,
      ),
    )
    
    0 讨论(0)
提交回复
热议问题