xZero xZero - 2 months ago 8
MySQL Question

PHP/MySQL - Merge duplicate values in output array

I know this question was already been asked before, but none seems to solve my problem.

I have DB where one user can have multiple rows. Only identifier for each is UID/UUID. Nothing else. Other values can be totally different.

I do the query which selects all rows in table. This returns an multidimensional array:

Array
(
[0] => Array
(
[meta] => 213097312903
[UUID] => 1
[data_name] => wheel_id
[data_value] => 13940
)

[1] => Array
(
[meta] => 2217037902293
[UUID] => 1
[data_name] => car_id
[data_value] => 09278149
)

[2] => Array
(
[meta] => 201207386198
[UUID] => 12
[data_name] => car_id
[data_value] => 639781238
)
)


What I would like to accomplish is to process given multidimensional array and merge all values for same UUID like this:

Array
(
[0] => Array
(
[meta] => 213097312903,2217037902293
[UUID] => 1
[data_name] => wheel_id,car_id
[data_value] => 13940,09278149
)

[1] => Array
(
[meta] => 201207386198
[UUID] => 12
[data_name] => car_id
[data_value] => 639781238
)
)


It doesn't to be exactly like this, I just don't want data for same user to be all around array.

For further processing, I need all users, so I cannot simply query select all where ID is...

I'm stuck with this. :(

Answer

You can loop that array and create a new one:

foreach($data as $value)
{
    $output[$value['UUID']]['meta'][] = $value['meta'];
    $output[$value['UUID']]['data_name'][] = $value['data_name'];
    $output[$value['UUID']]['data_value'][] = $value['data_value'];
}

if you want to convert the arrays to comma seperated values:

foreach($output as $uuid => $value)
{
    $outputWithCSV[$uuid]['meta'] = implode(",",$value['meta']);
    $outputWithCSV[$uuid]['data_name'] = implode(",",$value['data_name']);
    $outputWithCSV[$uuid]['data_value'] = implode(",",$value['data_value']);
}

$outputWithCSV would be:

Array
(
    [1] => Array
        (
            [meta] => 213097312903,2217037902293
            [data_name] => wheel_id,car_id
            [data_value] => 13940,09278149
        )

    [12] => Array
        (
            [meta] => 201207386198
            [data_name] => car_id
            [data_value] => 639781238
        )
)
Comments