从数组中删除重复项,保留一些值

时间:2014-03-23 03:21:50

标签: php arrays duplicates

我有一个像这样的PHP数组:

[0] => Array ( [0] => type [1] => value1 ) 
[1] => Array ( [0] => type [1] => value2 ) 
[2] => Array ( [0] => type [1] => value3 ) 
[3] => Array ( [0] => id [1] => value4 ) 
[4] => Array ( [0] => id [1] => value5 ) 
[5] => Array ( [0] => name [1] => value6 ) 
[6] => Array ( [0] => name [1] => value7 ) 
[7] => Array ( [0] => division [1] => value8 ) 
[8] => Array ( [0] => division [1] => value9 ) 
[9] => Array ( [0] => division [1] => value10 )

我需要将其更改为:

[0] => Array ( [0] => type [1] => value1,value2,value3 ) 
[3] => Array ( [0] => id [1] => value4,value5 )
[5] => Array ( [0] => name [1] => value6,value7 ) 
[7] => Array ( [0] => division [1] => value8, value9, value10 )

有没有办法这样做?

1 个答案:

答案 0 :(得分:1)

使用foreach和内部switch

foreach($arr as $k=>$arr1)
{
    switch ($arr1[0])
    {
        case 'type':$type.=$arr1[1].",";break;
        case 'id':$id.=$arr1[1].",";break;
        case 'name':$name.=$arr1[1].",";break;
        case 'division':$division.=$arr1[1].",";break;
    }
}

<强> OUTPUT :

Array
(
    [type] => value1,value2,value3
    [id] => value4,value5
    [name] => value6,value7
    [division] => value8,value9,value10
)

Working Demo