2013-04-17 211 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 –