简体   繁体   中英

Multidimensional array PHP from MYSQL query

I have the following tables in MYSQL:

CommentTable with columns: comment, commenter, datecommented and postid PostTable with columns: postid, dateposted

I perform this query in 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

where $postid array is an array of post ids.

The problem I have is when i'm trying to sort the query result into a multidimensional array.

I would want to have a multidimensional array called comment which would like this

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
    }
}

I'm doing this so that when I make a php echo I can loop out the comments relating to the specific post

For instance comment[0][1] would echo 'Comment 2 from first key in $postidarray'

Any help is appreciated.

You could do an ORDER BY shareTable.postId THEN BY shareTable.dateshared DESC

This would make all the rows with the same postId appear together so you could just check for a change of postId.

$i=-1;
$currentPostId=0;

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

This should give you the result you want. Alternately, If you use PDO, Use a prepared statement instead of using a single query with 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);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM