Combine array with same element value and keep them all together, comma separated

前端 未结 1 419
迷失自我
迷失自我 2021-01-16 04:18

I have a Multi-dimensional array

    [0] => Array
        (
            [name] => Size
            [value] => XS,S,XL
        )    
    [1] => Ar         


        
相关标签:
1条回答
  • 2021-01-16 05:15

    You can try this -

    $array = array(
    '0' => array
        (
            'name' => 'Size',
            'value' => 'XS,S,XL',
        ),    
    '1' => array
        (
            'name' => 'Brand',
            'value' => 'Adidas',
        ),    
    '2' => array
        (
            'name' => 'Size',
            'value' => 'XS,XL,L,M',
        ),    
    '3' => array
        (
            'name' => 'Brand',
            'value' => 'Nike',
        )
    );
    
    $temp = $new = array();
    foreach($array as $val) {
        $temp[$val['name']][] = $val['value'];
    }
    
    foreach($temp as $key => $value) {
        // merge values, fetch unique, then merge again
        $values = implode(',', array_unique(explode(',', implode(',', $value)))); 
        $new[] = array('name' => $key, 'value' => $values); // store 
    }
    
    var_dump($new);
    

    Output

    array(2) {
      [0]=>
      array(2) {
        ["name"]=>
        string(4) "Size"
        ["value"]=>
        string(11) "XS,S,XL,L,M"
      }
      [1]=>
      array(2) {
        ["name"]=>
        string(5) "Brand"
        ["value"]=>
        string(11) "Adidas,Nike"
      }
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题