使用相同的元素值组合数组,逗号分隔

时间:2016-12-30 06:08:33

标签: php arrays multidimensional-array

我有一个多维数组

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

我希望结果为

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

我已经搜索了答案但是没有找到任何解决方案 我正在尝试array_combinearray_merge甚至array_unique但没有成功

2 个答案:

答案 0 :(得分:2)

试试这个,

$result = array(); 
foreach($myArray as $value){
    $attribute_id = $value['attribute_id'];
    if(isset($result[$attribute_id]))
        $index = ((count($result[$attribute_id]) - 1) / 2) + 1;
    else
        $index = 1;

    $result[$attribute_id]['attribute_id'] = $attribute_id;
    $result[$attribute_id]['name'] = $value['name'];
    $result[$attribute_id]['value'] = $value['value'];        
}
$result = array_values($result);

答案 1 :(得分:1)

foreach($myArray as $val) {
        $temp[$val['name']]['values'][] = $val['value'];
        $temp[$val['name']]['attributeid'][] = $val['attribute_id'];
}
foreach($temp as $key => $value) {
        $values = implode(',', array_unique(explode(',', implode(',', $value['values'])))); 
        $attr = $value['attributeid'][0];
        $new[] = array('name' => $key, 'value' => $values,'attribute_id'=>$attr);
}

@Sougata Bose向我提出的相同逻辑