Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from array, preserving some values [closed]

I have a PHP array like this:

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

and I need to change it to this:

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

Is there any way to do so?

like image 264
Nidhin Chandran Avatar asked Apr 16 '26 02:04

Nidhin Chandran


1 Answers

Use a foreach and an inner 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

like image 181
Shankar Narayana Damodaran Avatar answered Apr 18 '26 14:04

Shankar Narayana Damodaran