0

I'm having issues with grouping an array returned from an SOQL query.

The array contents are as follows (this is a clipped version to give an idea of structure):

QueryResult Object
(
[queryLocator] => 
[done] => 1
[records] => Array
    (
        [0] => stdClass Object
            (
                [Id] => 
                [Contact] => 003b000000Ii7HcAAJ
                [Session] => stdClass Object
                    (
                        [Id] => 
                        [Name] => Future Leaders (Day1)
                    )

            )

        [1] => stdClass Object
            (
                [Id] => 
                [Contact] => 003b000000Ii6jtAAB
                [Session] => stdClass Object
                    (
                        [Id] => 
                        [Name] => Future Leaders Program (Day1)
                    )

            )

        [2] => stdClass Object
            (
                [Id] => 
                [Contact] => 003b000000Ii7MIAAZ
                [Session] => stdClass Object
                    (
                        [Id] => 
                        [Name] => Future Leaders Program (Day2)
                    )

            )

        [3] => stdClass Object
            (
                [Id] => 
                [Contact] => 003b000000KL4G4AAL
                [Session] => stdClass Object
                    (
                        [Id] => 
                        [Name] => Utilities Chat
                    )

            )

        [4] => stdClass Object
            (
                [Id] => 
                [Contact] => 003b000000Ii62fAAB
                [Session] => stdClass Object
                    (
                        [Id] => 
                        [Name] => Working Group Update
                    )

            )

    )

The issue is that the query returns duplicate contacts AND duplicate sessions so I want to sort this into a new array with distinct contacts and all sessions associated to the contact. Its an SOQL query so I cant SELECT DISTINCT and GROUP BY isn't giving me the correct results.

Any help would be really appreciated as my PHP skills are very rusty!

1 Answers1

0

One problem is that you have an array of objects. You are mixing arrays and objects. For your needs, I would step through the records array and make a new array with the contact as the key and the sessions as an array of objects for each key.

$contacts = array();
foreach($records as $record)
{
    if(!exists($contacts[$record->Contact]))
        $contacts[$record->Contact] = array();
    $contacts[$record->Contact][] = $record->Session;
}
kainaw
  • 4,256
  • 1
  • 18
  • 38