如何对数组项进行分类?

时间:2016-01-10 14:13:48

标签: php mysql arrays pdo

我有一个查询,它在一个页面中提取问题和答案的所有评论(每个页面至少包含一个帖子(问题),可能还有一个或多个帖子(答案))。现在我需要根据自己的问题或答案分开评论。

我的查询(提取所有评论)的结果是这样的:

while ($results = $sth->fetch(PDO::FETCH_ASSOC)) {
    echo '<pre>';        
    print_r($results);
}

/* Output:
            Array
            (
                 [id] => 1
                 [post_id] => 1
                 [content] => Have you any tried so far? 
            )

            Array
            (
                 [id] => 2
                 [post_id] => 3
                 [content] => Great answer, upvote 
            )

            Array
            (
                 [id] => 3
                 [post_id] => 3
                 [content] => That semicolon is redundant in line 5. Pplease edit it
            )

            Array
            (
                 [id] => 4
                 [post_id] => 2
                 [content] => Won't work ...!
            )

            Array
            (
                 [id] => 5
                 [post_id] => 3
                 [content] => @alex You are right thanks, Edited.
            )

因此,正如您在输出中看到的,所有注释都是混合的。现在我需要对它们进行分类。像这样:

/* NewOutput:

            [1] => Array
     post_id ^     (
                        [0] => Array
                               (
                                   [id] => 1
                                   [content] => Have you any tried so far?
                               )
                   )

            [2] => Array
     post_id ^     (
                        [0] => Array
                               (
                                   [id] => 4
                                   [content] => Won't work ...!
                               )
                   )

            [3] => Array
     post_id ^     (
                        [0] => Array
                               (
                                   [id] => 2
                                   [content] => Great answer, upvote
                               )

                        [1] => Array
                               (
                                   [id] => 3
                                   [content] => That semicolon is redundant in line 5. Pplease edit it
                               )

                        [2] => Array
                               (
                                   [id] => 5
                                   [content] => @alex You are right thanks, Edited.
                               )
                   )

嗯,现在我想知道,如何根据数组中特定键的值创建嵌套数组?就像上面一样。

1 个答案:

答案 0 :(得分:2)

试试这个......

$output = array();
foreach($results as $r){
    $key = "post_".$r["post_id"];
    if(!array_key_exists($key, $output)){
        $output[$key] = array();
    }
    array_push($output[$key], array("id"=>$k["id"], "content"=>$k["content"]));
}
print_r($output);