【问题标题】:Multidimensional array PHP from MYSQL query来自 MYSQL 查询的多维数组 PHP
【发布时间】:2013-04-17 18:06:04
【问题描述】:

我在 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 时可以循环出与特定帖子相关的 cmets

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

感谢任何帮助。

【问题讨论】:

  • 获取不到多维数组。在您的语句中使用 GROUP 并从结果集中创建(如果真的需要)您的数组。
  • 对不起我没有关注
  • 可以得到一个多维数组。请看下面的解决方案。

标签: php mysql multidimensional-array


【解决方案1】:

你可以做一个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);
 }

【讨论】:

  • 好的,输出是我想要的,但它没有将注释放在第二个数组@2bigpigs
  • 好的,所以我稍微调整了一下——我用 $comment[$i] = $res['comment'] 替换了 $comment[$i] =$res。 mysql 代码 ORDER BY shareTable.postId THEN BY shareTable.dateshared DESC 不起作用。你能帮我解决这个问题,以便我接受你的答案吗?谢谢@2bigpigs
  • 好吧,任何有此问题的人的正确语法是按 shareTable.posid desc、shareTable.dateShared desc 排序
猜你喜欢
  • 2015-04-30
  • 2018-02-11
  • 2011-06-30
  • 2014-05-04
  • 1970-01-01
  • 2017-12-18
  • 2014-04-08
  • 2017-06-14
  • 1970-01-01
相关资源
最近更新 更多