来自MYSQL查询的多维数组PHP

时间:2013-04-17 18:06:05

标签: php mysql multidimensional-array

我在MYSQL中有以下表格:

CommentTable with columns: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数组是post 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回音时,我可以循环出与特定帖子相关的评论

例如注释[0] [1]将回复'$ postidarray'中第一个键的评论2

感谢任何帮助。

1 个答案:

答案 0 :(得分: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);
 }