PHP - 来自SOQL的数组分组结果

时间:2015-01-26 16:50:12

标签: php arrays multidimensional-array soql

我在对从SOQL查询返回的数组进行分组时遇到问题。

数组内容如下(这是一个剪辑版本,可以了解结构):

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
                    )

            )

    )

问题是查询返回重复的联系人和重复的会话,因此我想将其排序为具有不同联系人的新阵列以及与联系人关联的所有会话。它是一个SOQL查询所以我不能选择DISTINCT和GROUP BY并不能给我正确的结果。

任何帮助都会非常感激,因为我的PHP技能非常生疏!

1 个答案:

答案 0 :(得分:0)

一个问题是你有一个对象数组。您正在混合数组和对象。为了满足您的需求,我将遍历记录数组并创建一个新的数组,其中联系人作为键,会话作为每个键的对象数组。

$contacts = array();
foreach($records as $record)
{
    if(!exists($contacts[$record->Contact]))
        $contacts[$record->Contact] = array();
    $contacts[$record->Contact][] = $record->Session;
}