2013-04-17 213 views
0

我在MYSQL下表:多维数组PHP

CommentTable与列:评论,评论者,datecommented和帖子ID PostTable与列:帖子ID,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{ 

[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]会回应'评论2从第一把钥匙在$ postidarray'

任何帮助表示赞赏。

+0

你不能得到一个多维数组。在你的语句中使用GROUP,并从结果集中创建(如果真的需要)你的数组。 – djot

+0

对不起,我不关注 –

+0

你可以得到一个多维数组。请看下面的解决方案。 –

回答

0

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

这将使所有使用相同的帖子ID行一起出现,所以你可以只检查的帖子ID的变化。

$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); 
} 
+0

好的输出结果是我想要的但它不会把注释放在第二个数组中@ 2bigpigs –

+0

好吧,我调整了一下 - 我用$ comment替换了$ comment [$ i] = $ res [ $ i] = $ res ['comment']。 mysql代码ORDER BY shareTable.postId THEN BY shareTable.dateshared DESC不起作用。你能帮助我吗?这样我就可以接受你的答案了吗?谢谢@ 2bigpigs –

+0

好吧任何人遇到这个问题的正确语法是order by shareTable.posid desc,shareTable.dateShared desc –