SQL连接两个表来给出多数组结果

时间:2016-04-06 17:47:27

标签: php mysql arrays join mysqli

我有2个表 using (Graphics gra = Graphics.FromImage(imgOriginal)) { Bitmap bmLogo = new Bitmap(imgLogo); int nWidth = bmLogo.Size.Width; int nHeight = bmLogo.Size.Height; int nLeft = (imgOriginal.Width / 2) - (nWidth / 2); int nTop = (imgOriginal.Height / 2) - (nHeight / 2); gra.DrawImage(bmLogo, nLeft, nTop, nWidth, nHeight); // Convert the image to byte[] System.IO.MemoryStream stream = new System.IO.MemoryStream(); bitmap.Save(bmLogo, System.Drawing.Imaging.ImageFormat.Bmp); byte[] imageBytes = bmLogo.ToArray(); // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); // Write the bytes (as a Base64 string return base64String; } eventscategories表有2列categoriesidcategory表包含event作为category_id表的外键。

现在categories表的内容由

给出
events

现在我要做的是选择所有行并以

的形式产生输出
+------------------------------------------------------+
| id | category_id | event_name | event_date | created |
+------------------------------------------------------+
| 1  |     1       | event 1    | 12-04-2016 |TIMESTAMP|
| 2  |     1       | event 2    | 14-04-2016 |TIMESTAMP|
| 3  |     2       | event 1    | 16-04-2016 |TIMESTAMP|
| 4  |     1       | event 3    | 14-04-2016 |TIMESTAMP|
| 5  |     2       | event 2    | 12-04-2016 |TIMESTAMP|
+------------------------------------------------------+

如何做到这一点。我正在使用=> Category 1 <> event 1 <><> 12-04-2016 <> event 2 <><> 14-04-2016 <> event 3 <><> 14-04-2016 => Category 2 <> event 1 <><> 16-04-2016 <> event 2 <><> 12-04-2016 PHP,我希望将此信息存储在PHP数组中,以便我可以使用PHP mysqli循环或for

1 个答案:

答案 0 :(得分:2)

按类别,事件名称

对查询进行排序
SELECT  categories.category,
        events.event_name

FROM categories

    LEFT JOIN events
    ON events.category_id = categories.id

ORDER BY categories.category, events.event_name

然后遍历结果以构造所需的多维数组:

$data = array();

foreach($results as $row){
    $data[$row['category']][$row['event_name']]['event_name'] = $row['event_name'];
    $data[$row['category']][$row['event_name']]['event_date'] = $row['event_date'];
}

然后你可以执行这样的嵌套迭代输出:

foreach($data as $category => $events){

    echo $category.'<br>';

    foreach($events as $event){
        echo '    <> '.$event['event_name'].'<br>';
        echo '        <> '.$event['event_date'].'<br>';
    }

}

不是使用事件/类别名称作为多维数组的索引,而是可以获取事件ID,并在名称不是唯一的情况下使用它。