从MySQL查询结果创建和使用关联数组 - PHP

时间:2014-09-23 09:25:56

标签: php mysql sql arrays

我有一个SQL查询,用数字键选择用餐选项。我想将每个数字键与膳食名称相关联。以下查询仅显示膳食号码(这是正确的)我无法与ID匹配,因为我会得到错误的结果。

Array
(
    [meal_1] => 1
    [meal_2] => 2
    [meal_3] => 1
)
Array
(
    [meal_1] => 2
    [meal_2] => 1
    [meal_3] => 2
)
Array
(
    [meal_1] => 0
    [meal_2] => 3
    [meal_3] => 3
)
Array
(
    [meal_1] => 2
    [meal_2] => 4
    [meal_3] => 0
)

但我想像这样输出

Array
(
    [meal_1] => Soup
    [meal_2] => Salmon
    [meal_3] => Torte
)
Array
(
    [meal_1] => Salad
    [meal_2] => Chicken
    [meal_3] => Tart
)
Array
(
    [meal_1] => No
    [meal_2] => Pasta
    [meal_3] => Brulee
)
Array
(
    [meal_1] => Salad
    [meal_2] => Burger
    [meal_3] => Pate
)

$result = mysql_query("SELECT Meal_table_1.meal_1, Meal_table_1.meal_2, Meal_table_1.meal_3 FROM Meal_table_1 ");
echo "<pre>";
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
echo "</pre>";
mysql_free_result($result);

//Meal_table_1

+----+--------+-------+-------+
| ID | meal_1 | meal_2| meal_3|
+----+--------+-------+-------+
|  1 | 1      | 2     | 1     |
|  2 | 2      | 1     | 2     |
|  3 | 0      | 3     | 3     |
|  4 | 2      | 4     | 0     |
+----+--------+-------+-------+

$meal_1 = array('0' => 'No','1' => 'Soup','2' => 'Salad','3' => 'Pate');

$meal_2 = array('0' => 'No','1' => 'Chicken','2' => 'Salmon','3' => 'Pasta','4' => 'Burger');

$meal_3 = array('0' => 'No','1' => 'Torte','2' => 'Tart','3' => 'Brulee',);

// Meal_table_2 (should this be in three separate tables?)

+----+--------+--------+--------+
| ID | starter| main   | dessert|
+----+--------+--------+--------+
|  1 | Soup   | Chicken| Torte  |
|  2 | Salad  | Salmon | Tart   |
|  3 | Pate   | Pasta  | Brulee |
|  4 |        | Burger |        |
+----+--------+--------+--------+

1 个答案:

答案 0 :(得分:0)

您现在的查询是:

SELECT Meal_table_1.meal_1, Meal_table_1.meal_2, Meal_table_1.meal_3 FROM Meal_table_1

您的查询可能是:

SELECT tstarter.starter, tmain.main, tdessert.dessert
FROM Meal_table_1 meal
LEFT OUTER JOIN Meal_table_2  tstarter
ON meal.ID = tstarter.id
LEFT OUTER JOIN Meal_table_2  tmain
ON meal.ID = tmain.id
LEFT OUTER JOIN Meal_table_2  tdessert
ON meal.ID = tdessert.id

但最好改变meal_table_2的结构(并给你的表一个更好的名字!)

+----+---------+---------+
| ID | type    | main    |
+----+---------+---------+
|  1 | starter | Soup    |
|  1 | main    | Chicken | 
|  1 | dessert | Torte   |
|  2 | starter | Salad   |
|  2 | main    | Salmon  |
|  2 | dessert | Tart    |
|  3 | starter | Pate    |
|  3 | main    | Pasta   |
|  3 | dessert | Brulee  |
|  4 | main    | Burger  |
+----+---------+---------+

除非ID必须相同,否则最好为每一行提供自己的ID。也许你甚至不再需要这种类型了?