根据特定的mysql列对JSON输出进行分组

时间:2015-06-09 16:06:34

标签: php mysql json mysqli

我有一个mysql表(名称:"消息" ),它有三列,如下所示:

messageID,fromUserID,content

我希望使用如下格式的php脚本输出json;我需要分发每个用户的消息( fromUserID 列)。

JSONOutput:

{
"newCount":"x",
"messages":
[
    {
        "fromUserID":"x",
        "messagesArray":
        [
            {"messageID":"x","content":"xxx"},
            {"messageID":"x","content":"xxx"},
            {"messageID":"x","content":"xxx"}                
        ]
    },
    {
        "fromUserID":"y",
        "messagesArray":
        [
            {"messageID":"x","content":"xxx"},
            {"messageID":"x","content":"xxx"},
            {"messageID":"x","content":"xxx"}                
        ]
    },
    {
        "fromUserID":"z",
        "messagesArray":
        [
            {"messageID":"x","content":"xxx"},
            {"messageID":"x","content":"xxx"},
            {"messageID":"x","content":"xxx"}                
        ]
    }
]
}

我的PHP脚本:

$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");

$outputArray = array();

$outputArray['hasNew'] = mysqli_num_rows($query);

$messagesArray = array();

if($query)
{
    while($row = mysqli_fetch_assoc($query))
    {
        $MSGArray = array();
        $messagesArray['fromUserID'] = $row['fromUserID'];
        $MSGArray['messageID'] = $row['messageID'];
        $MSGArray['content'] = $row['content'];
        $messagesArray['MessagesArray'][] = $MSGArray;      
    }
    $outputArray['Messages'][] = $messagesArray;
}

echo json_encode($outputArray);

但是上面的脚本我给出了错误的结果如下:

{
"hasNew":6,
"Messages":
[
 {
  "fromUserID":"24",
  "MessagesArray":
  [
   {"messageID":"4","content":"test"},
   {"messageID":"3","content":"test"}, 
   {"messageID":"6","content":"test"},
   {"messageID":"5","content":"test"},
   {"messageID":"1","content":"test"},
   {"messageID":"2","content":"test"}
  ]
 }
]
}

我的PHP脚本只使用最后的 fromUserID 值来分组消息!!!

请让我知道我错在哪里......

1 个答案:

答案 0 :(得分:1)

试试吧

if($query)
{
    while($row = mysqli_fetch_assoc($query))
    {
        $MSGArray = array();
        $messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
        $MSGArray['messageID'] = $row['messageID'];
        $MSGArray['content'] = $row['content'];
        $messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;      
    }
foreach($messagesArray as $value) {
    $outputArray['Messages'][] =  $value;
}
}