php - 如何按类别列出评论? (操作数组)

标签 php arrays

我有一个名为 $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/

相关文章:

php - 如何将 MySQL 数据检索到 PHP 数组中,然后使用该数组运行另一个查询?

c - c中的字符串文字

PHP file_put_contents 和 UTF-8

php - 使用 php 表单将数据输入到 2 个 MySql 表中

java - 为什么我的长整数会稍微改变一点?

javascript - 通过 PHP 将 mySQL 数据拉入 Javascript 对象数组

c# - 将字符串数组打印到txt文件

Java编程,寻找数组中某个键的连接

java - 在 Java 中如何获取数组、集合或字符串的大小?

php - 浏览器可以使用 POST 重定向到 url 吗?