Json来自PHP中的两个mysql表

时间:2014-02-18 20:15:45

标签: php mysql json

我正在尝试从两个相关的MySQL表构建一个json输出。 我有一个“餐馆”表和表“菜肴”餐馆表中的每个项目在Dishes表中有几个相关项目,由id引用。每个餐厅项目ID都是Dishes表中的外键,为f_id。

例如: 餐厅餐桌

+----+-------------+-----------+
| Id |    Name     | Misc Info |
+----+-------------+-----------+
|  1 | Restaurant1 | Some Info |
+----+-------------+-----------+

菜肴表

+----+------+-----------+-------------+
| Id | f_id |   dish    | description |
+----+------+-----------+-------------+
|  1 |    1 | DishName  | DishDesc.   |
|  2 |    1 | DishName2 | DishDesc.   |
+----+------+-----------+-------------+

我想从那些表创建一个JSON输出,如下所示:

{
    "Restaurants": [
        {
            "name": "String content",
            "misc info": "String content"
            "Dishes": [
                {
                    "dish": "String content",
                    "description": "String content"

                },
                {
                    "dish": "String content",
                    "description": "String content"
                }
            ],

        },
        {
            "name": "String content",
            "misc info": "String content"
            "Dishes": [
                {
                    "dish": "String content",
                    "description": "String content"
                },
                {
                    "dish": "String content",
                    "description": "String content"
                }
            ],

        }
    ]
}

我使用PHP和mysql_query方法来计算逻辑,我计划在生产版本中使用PDO。这是我到目前为止尝试过的代码。

//Create Our Query
$srtResult = "SELECT * FROM Restaurants";

//Execute Query
$result=mysql_query($srtResult);
//Iterate Throught The Results

while ($row = mysql_fetch_assoc($result)) {
    $count = $row['id'];
    $srtResult2 = "SELECT * FROM Dishes WHERE id = $count";
    $result2 = mysql_query($srtResult2);
    while(mysql_num_rows($result2)){
        $dishes = mysql_fetch_row($result2);
        $dishList[] = Array(
            "dish" => $dishes[3],
            "description" => $dishes[4]);
    }
    $json['Restaurants'][] = 
        Array("Restaurants" => Array(
                "name" => $row['name'], 
        "Dishes" => Array(
            $dishList)));
}
header('Content-type: application/json');
echo json_encode($json);

我遇到的问题是菜肴不会根据当前的餐厅项目进行迭代,对于每个餐馆项目,我都会从第一家餐厅获得菜肴。 我认为问题在于循环本身,因为我在每个Restaurant包装器中获得了不同的int计数。任何帮助都会非常感激,我已经做了好几天了,并且已经用尽了基本的PHP知识。

2 个答案:

答案 0 :(得分:2)

您正在使用大量查询。为什么不在一个查询中执行此操作?

SELECT * FROM `Restaurants` `r`
    LEFT JOIN `Dishes` `d` ON (`r`.`id` = `d`.`f_id`)
ORDER BY `r`.`id` ASC 

然后使用结果构建JSON对象。

EDIT 为了更容易迭代结果,我将Query更改为:

SELECT 
`r`.`id` as `restaurantId`, 
`r`.`name`, 
`r`.`info`, 
`d`.`id` AS `dishId`,
`d`.`dish`,
`d`.`description`
FROM `restaurants` `r`
    LEFT JOIN `dishes` `d` ON (`r`.`id` = `d`.`f_id`)
ORDER BY `r`.`id` ASC

结果将如下所示: restaurantId, name, info, dishId, dish, description

您现在可以像这样迭代结果:

$jsonArray = array();

foreach ($record as $dishDetails){
    // details of the restaurant
    $jsonArray[$dishDetails['f_id']]['name'] = $dishDetails['name'];
    $jsonArray[$dishDetails['f_id']]['info'] = $dishDetails['info'];

    // build the dishes of the restaurant
    $jsonArray[$dishDetails['f_id']]['dishes'][$dishDetails['dishId']]['dish'] = $dishDetails['dish']
    $jsonArray[$dishDetails['f_id']]['dishes'][$dishDetails['dishId']]['description'] = $dishDetails['description']
}

答案 1 :(得分:0)

这是我使用的有效解决方案:

<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
function __autoload($classname) {
    $filename = "classes/". $classname.".class.php";
    include_once($filename);
}`enter code here`
$recepie=new recepie(new database());
$recepies=mysql_query("SELECT * FROM recepies");
while ($recipe=mysql_fetch_assoc($recepies,MYSQL_ASSOC))
{
$rec_id=$recipe['rec_id'];
$ingredients=mysql_query("SELECT * FROM recepie_ingredients WHERE rec_id=".$rec_id);

unset($ing);
$ing= array();
  while($ingredient=mysql_fetch_assoc($ingredients,MYSQL_ASSOC))
    {
                    $ing[]=array("ing_id"=>$ingredient['ing_id'],
                               "ing_name"=>$ingredient['ing_name'],
                               "ing_amount"=>$ingredient['ing_amount'],
                                "ing_unit"=>$ingredient['ing_unit']);
    }

                     $json["Recepies"][]=array( "rec_id"=>$recipe['rec_id'], 
                                                "rec_name"=>$recipe['rec_name'],
                                                "rec_image"=>$recipe['rec_image'],
                                                "rec_createby"=>$recipe['rec_createby'],
                                                "rec_createdate"=>$recipe['rec_createdate'],
                                                "rec_description"=>$recipe['rec_description'],
                                                "rec_Ingredients"=>$ing );


}
echo json_encode($json);   

?>