Skip to content
Advertisement

php array unique and pushing data

i got data return from mongodb and as i searched i saw that i cannot user cursor twice so i put all data in arrays and now i need to split the data to unique name, the data i got :

Array
(
    [0] => Array
        (
            [name] => 208
            [data] => 150
        )

    [1] => Array
        (
            [name] => 208
            [data] => 130
        )

    [2] => Array
        (
            [name] => 204
            [data] => 20
        )

    [3] => Array
        (
            [name] => 204
            [data] => 30
        )

    [4] => Array
        (
            [name] => 208
            [data] =>300
        )
)

what i need to accomplish is to get unique names and push Data return for each name like that:

[0] => Array
        (
            [name] => 208
            [data] => [150,130,300]
        )

    [1] => Array
        (
            [name] => 204
            [data] => [20,30]
        )
)

i can get the unique Name’s but not pushing the data value to each name

i tried with two foreach loops without success , thanks for any help

foreach ($cursor as $document) { 
    $name[] = $document['name']; 
    $data[] = $document['data']; 
} 
$uniName = array_unique($name); 
foreach($uniName as $theName) { 
    foreach($result as $two) { 
        $arr1['name'] = $two['name']; 
        if($theName == $towo['name']) { 
            $arr1['data'][] = $tow['data']; 
        } 
        array_push($result1,$arr1); 
    } 
} 

Advertisement

Answer

A simple foreach loop can be used to create a new array. If you use the 'name' as the key then this makes it easy to remove the duplicates. All you have to do is check if you saw this name before and if not create a new entry in the new array and if you saw this name before just add a data item to the data array.

$dataArray = 
[
    ['name'=> 208, 'data' =>150],
    ['name'=> 208, 'data' =>130],
    ['name'=> 204, 'data' =>20],
    ['name'=> 204, 'data' =>30],
    ['name'=> 208, 'data' =>300]
];


foreach ($dataArray as $key=>$sub){
    if ( isset($new[$sub['name']]) ) {
        // we saw this one before
        $new[$sub['name']]['data'][] = $sub['data'];
    } else {
        // first time we saw this one
        $new[$sub['name']] = ['name' => $sub['name'], 'data' => [$sub['data']]];
    }
}
$new = array_values($new);
print_r($new);

RESULT

Array
(
    [0] => Array
        (
            [name] => 208
            [data] => Array
                (
                    [0] => 150
                    [1] => 130
                    [2] => 300
                )

        )
    [1] => Array
        (
            [name] => 204
            [data] => Array
                (
                    [0] => 20
                    [1] => 30
                )
        )
)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement