我有一个名为 $comments
的数组。
当我 var_dump($comments);
这是结果。
array
0 =>
object(stdClass)[11]
public 'comment_id' => string '1' (length=1)
public 'comment_article_id' => string '1' (length=1)
public 'comment_user_id' => string '2' (length=1)
public 'comment' => string 'Comment to article_id 1' (length=11)
public 'comment_date' => string '2016-03-10 20:06:43' (length=19)
1 =>
object(stdClass)[9]
public 'comment_id' => string '3' (length=1)
public 'comment_article_id' => string '1' (length=1)
public 'comment_user_id' => string '2' (length=1)
public 'comment' => string 'Another comment to article_id 1.' (length=14)
public 'c
' => string '2016-03-10 20:06:43' (length=19)
2 =>
object(stdClass)[6]
public 'comment_id' => string '5' (length=1)
public 'comment_article_id' => string '2' (length=1)
public 'comment_user_id' => string '2' (length=1)
public 'comment' => string 'Comment to article_id 2' (length=26)
public 'comment_date' => string '2016-03-10 20:06:43' (length=19)
这是我的函数,它给出了上面的结果:
public function ListComments($userid) {
$comments = $this->FindComments($userid);
var_dump($comments);
}
我想列出这样的评论:
- 1 (which is comment_article_id)
-Comment to article_id 1
-Another comment to article_id 1.
- 2
-Comment to article_id 2
我不知道如何操纵我当前的数组来获得这样的结果。
我想在不对 FindComments()
函数进行任何更改的情况下将其存档。
我必须在 ListComments()
函数中完成所有我必须做的事情。
可能我需要一个 foreach 循环,但我没有申请。
最佳答案
要通过操作您已收到的评论数组来实现此目的,您只需遍历它并将所有元素放入二维关联数组中,其中键是文章 ID
$results = []; //$result = array() if using below php 5.4
foreach ($comments as $comment) {
$results[$comment->comment_article_id][] = $comment;
}
ksort($result); //to sort from lowest highest article id
然后要按照您的意愿输出它,您只需要遍历 $results
数组和所有注释即可打印内容。
Please note that I consider echo-ing html as a bad practice. It's just to quickly show you how to achieve the output you desired.
echo '<ul>';
foreach ($results as $key => $comments) {
echo '<li>' . $key . '</li>';
echo '<ul>';
foreach($comments as $comment) {
echo '<li>' . $comment->comment . '</li>';
}
echo '</ul>';
}
echo '</ul>';
关于php - 如何按类别列出评论? (操作数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36006409/