我有一个查询,它在一页中获取所有问题和答案的评论(每个页面至少包含一个帖子(问题),并且可能加上一个或多个帖子(答案))。现在我需要根据自己的问题或答案来分隔评论。
我的查询结果(获取所有评论)是这样的:
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.
)
)
那么,现在我想知道,如何根据数组中特定键的值创建嵌套数组?和上面完全一样。
最佳答案
试试这个...
$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);
关于php - 如何对数组项进行分类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706390/