按数组中的字段对项目进行分组

时间:2014-09-03 06:52:27

标签: php json rest kohana

[
            {
                "type": "photo",
                "username": "Зубр Зубров",
                "user_id": "816",
                "avatar": "images/eb/ebffefae4de882a26e02d78f5c493477",
                "date_from": "2014-09-03 12:22:50",
                "comments_count": 0,
                "image": "images/e6/e6069bfcf0beb79100789ffc458c7ff0",
                "image_id": "5924",
                "likes_count": 0,
                "is_liked": false
            },

            {
                "type": "photo",
                "username": "Зубр Зубров",
                "user_id": "816",
                "avatar": "images/eb/ebffefae4de882a26e02d78f5c493477",
                "date_from": "2014-09-03 12:19:15",
                "comments_count": 0,
                "image": "images/37/37c544d487727b8b6a5d199980fd55e2",
                "image_id": "5923",
                "likes_count": 0,
                "is_liked": false
            },
            {
                "type": "photo",
                "username": "Eugene",
                "user_id": "574",
                "avatar": "images/b1/b1722a365c2397d30217ca2cdaefc745",
                "date_from": "2014-09-02 21:10:19",
                "comments_count": 1,
                "image": "images/d4/d471840fa2391268cbff66b568a5d214",
                "image_id": "5922",
                "likes_count": 1,
                "is_liked": true
            }
        ]

以上回复,是我从服务器生成的json。我必须对项目进行分组,其中date_from字段与其他项目在1小时或更短的时间间隔内。在上述情况下,前两个项应该分组,因为它们之间的date_from间隔接近3分钟。也许我应该在sql级别上,但现在的目标是在PHP代码中。 Groupping结果应输出带有分组项的子数组

1 个答案:

答案 0 :(得分:0)

通常用于分组使用O(1)哈希的好主意。因此,您应该遍历数组并使用" 2014-09-03 12"设置新的散列数组。字符串的一部分作为键,数组作为值。添加到该阵列所需的一切。

我很久以前写过php,但在python中看起来很相似:

grouping = {}  # hashing array
for elem in elements:
    grouping_key = elem["date_from"].split(':')[0] # or if you are sure about format: elem["date_from"][:13] - the first 13 characters
    if grouping_key not in grouping.keys():
        grouping[grouping_key]= [] # new array
    grouping[grouping_key].append(elem)

现在你应该有2个小组。