Foreach changed row

久未见 提交于 2020-01-16 00:44:47

问题


I'm trying to manipulate my MySQL results to create an XML file. This question is not to do with the latter part of that task, but the former: manipulating the SQL query results in PHP.

I want to create a foreach statement which will group the results into the column value they share ('group_id'). (I might have three rows with the same column value, and five rows with another column value.)

I imagine having one foreach construct inside another one. The parent one should loop through the results by the shared column value ('group_id'), and the second should loop through based on another column ('message_content').

This is a suggestion of my data (actual data, here: http://sqlfiddle.com/#!2/4ce52/1):

message_id |  group_id  |  message_content  |  group_name

1          |  1         |  ........         |  ........
2          |  1         |  .......          |  .......
3          |  1         |  ......           |  ......
4          |  2         |  .....            |  .....
5          |  2         |  ....             |  ....
6          |  3         |  ...              |  ...
7          |  4         |  ..               |  ..
8          |  4         |  .                |  .

This is a suggestion of my PHP code. (Remember, I'm trying to construct an XML file based on the data.)

foreach ($results['group_id'] AS $group)
{
   // <group_name>

   foreach ($results['message_id'] AS $message)
   {
      // <message_content>

      // <message_content>
   }       

   // </group_name>
}

回答1:


If you use anORDER BY clause in your SQL query to order by the group_id, then something like this should achieve what you want;

$groupId = null;
foreach ($results as $message) {
    if ($message['group_id'] !== $groupId) {
        if (!is_null($groupId)) {
            echo '</group>';
        }
        echo "<group id=\"{$message['group_id']}\">";
        $groupId = $message['group_id'];
    }
    echo "<message id=\"{$message['message_id']}\">{$message['message_content']}</message>";
}
if (!is_null($groupId)) {
    echo '</group>';
}


来源:https://stackoverflow.com/questions/23915297/foreach-changed-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!