0

我在 MYSQL 中有以下表:

带有列的 CommentTable:comment、commenter、datecommented 和 postid 带有列的 PostTable:postid、dateposted

我在 php 中执行此查询

Select commentTable.comment, commentTable.commenter, commentTable.datecommented, shareTable.postid, shareTable.dateshared  from shareTable Left Join commentTable on commentTable.postid = shareTable.postid where shareTable.postid IN ($postidarray) order by  shareTable.dateshared desc

其中 $postid 数组是一个帖子 ID 数组。

我遇到的问题是当我尝试将查询结果排序到多维数组中时。

我想要一个名为 comment 的多维数组,它会像这样

Comment{

[0] {
       [0] => "Comment 1 from first key in $postidaray"
       [1] =>  "Comment 2 from first key in $postidarray"
    }

[1] {
       [0] => "Comment 1 from second key in $postidarray"
     } // assuming there is only one comment for the second key in $postidarray

[2]{

       [0] => "Comment 1 from third key in $postidarray"
       [1] =>  "Comment 2 from third key in $postidarray"
       [2] =>  "Comment 3 from third key in $postidarray"
       [3] =>  "Comment 4 from third key in $postidarray"
   } 
   // assuming there are 4 comments for the third key in $postidarray
    }
}

我这样做是为了当我做一个 php echo 时,我可以循环出与特定帖子相关的评论

例如,comment[0][1] 会回显“来自 $postidarray 中第一个键的评论 2”

任何帮助表示赞赏。

4

1 回答 1

0

你可以做一个ORDER BY shareTable.postId THEN BY shareTable.dateshared DESC

这将使具有相同 postId 的所有行一起出现,因此您可以检查 postId 的更改。

$i=-1;
$currentPostId=0;

$comment = array();
 while($assoc = mysql_fetch_assoc($res)){
     if($assoc['postId']!=$currentPostId){
              $currentPostId = $assoc['postId'];
              $i++;
     }
  $comment[$i][] = $res;
}

这应该会给你你想要的结果。或者,如果您使用 PDO,请使用准备好的语句而不是使用单个查询IN( ... )

$stmt = $pdo->prepare("Select ... shareTable.postid=? order by ShareTable.dateshared desc");
 $comment = array();
$p = &$postIds[0];
$stmt->bindParam($p);
 foreach($postIds as $p){
      $stmt->execute();
      $comment[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
 }
于 2013-04-17T18:34:38.253 回答