编程语言
首页 > 编程语言> > php-将具有相同元素值的数组组合在一起,并将它们放在一起,并用逗号分隔

php-将具有相同元素值的数组组合在一起,并将它们放在一起,并用逗号分隔

作者:互联网

我有一个多维数组

    [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
        )

我想要结果

[0] => Array
    (
        [name] => Size
        [value] => S,M,L,XS,XL
    )    
[1] => Array
    (
        [name] => Brand
        [value] => Adidas,Nike
    )

我正在尝试array_combine,array_merge甚至array_unique没有成功

解决方法:

你可以试试这个-

$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);

产量

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

标签:codeigniter-3,php,arrays,multidimensional-array
来源: https://codeday.me/bug/20191009/1881990.html