Skip to content
Advertisement

Create or reorder an array based on values from array of objects

I have an array of objects, a portion of which looks like this:

[Results] => Array
    (
        [0] => stdClass Object
            (
                [Id] => 3103
                [Tag] => Atticus Ross
            )

        [1] => stdClass Object
            (
                [Id] => 3105
                [Tag] => Atticus Ross
            )

        [2] => stdClass Object
            (
                [Id] => 3106
                [Tag] => Grant Marshall
            )

        [3] => stdClass Object
            (
                [Id] => 3107
                [Tag] => Trent Reznor
            )

        [4] => stdClass Object
            (
                [Id] => 3108
                [Tag] => Atticus Ross
            )

        [5] => stdClass Object
            (
                [Id] => 3109
                [Tag] => Atticus Ross
            )

        [6] => stdClass Object
            (
                [Id] => 3110
                [Tag] => Grant Marshall
            )
        [7] => stdClass Object
            (
                [Id] => 3114
                [Tag] => Trent Reznor
            )    
    )

[Id] is unique.

[Tag] is not unique.

I need to restructure this so I know which Ids correspond to each Tag. Each Tag should only be listed once. Something like:

Array
(
    [Atticus Ross] => Array
        (
            [0] => 3103
            [1] => 3105
            [2] => 3108
            [3] => 3109
        )
    [Grant Marshall] => Array
        (
            [0] => 3106
            [1] => 3110
        )   
    [Trent Reznor] => Array
        (
            [0] => 3107
            [1] => 3114
        )        
)

It doesn’t necessarily need to be structured like that, but hopefully makes it easier to see what I’m looking for.

I’ve tried looping through the original array, and I’m able to get a unique array of Tags, but I’m not sure how to add/merge the Ids for each Tag:

$all_tags = array();

foreach ($results as $result) {
    $Id = $result->Id;
    $Tag = $result->Tag;

    $all_tags[] = $Tag;
    $all_tags_unique = array_values(array_unique($all_tags));
}

I may be way off here. Appreciate any help!

Advertisement

Answer

It should be enough just to loop through the result elements and add them to an element identified by the Tag…

$all_tags = array();

foreach ($results as $result) {
    $all_tags[ $result->Tag ][] = $result->Id;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement