【问题标题】:Two MySQL queries in JSON objectsJSON 对象中的两个 MySQL 查询
【发布时间】:2013-09-13 15:48:45
【问题描述】:

我正在尝试通过 MySQL 和 PHP 构建以下 JSON。
每个章节都有一个 ID、一个章节标题和一个主题列表。
每个主题都有一个id和一个主题区域

{
"Chapters": [
    {
        "id": "1",
        "chapterTitle": "Introduction",
        "Topics": [
            {
                "id": "1",
                "topicArea": "C++"
            },
            {
                "id": "2",
                "topicArea": "Java"
            }
        ]
    },
    {
        "id": "2",
        "chapterTitle": "Getting Started",
        "Topics": [
            {
                "id": "1",
                "topicArea": "Start Here"
            }
        ]
    }
 ]
}

但是,如果我尝试以下 PHP 代码 (1),我将无法生成此输出

//Get all chapters
$result = mysql_query("SELECT * FROM chapters");      

while ($row = mysql_fetch_array($result))
{
    $json[] = $row;
    $json2 = array();
    $chapterid = $row["id"];

    //Fetch all topics within the first book chapter
    $fetch = mysql_query("SELECT id,topicArea FROM topics where chapterid=$chapterid");
    while ($row2 = mysql_fetch_assoc($fetch))
    {
         $json2[] = array( 
            'id' => $row2["id"],
            'topicArea' => $row2["topicArea"]
           );
     }
     $json['Topics'] = $json2;          //I think the problem is here!
}
echo json_encode($json);

【问题讨论】:

  • 查看 SQL 注入和 SQL 参数以修复它。
  • $json['Topics'][] = $json2; 否则会被覆盖
  • 您告诉我们出了点问题,但您并没有告诉我们您得到的结果。我们需要看到这一点,以便做的不仅仅是指出逻辑缺陷。

标签: php mysql arrays json


【解决方案1】:

请不要再使用mysql_* 函数。 mysqliPDO 都允许您使用准备好的语句。

话虽如此,你说得对,$json['Topics'] = $json2; 是问题所在:这需要是$json['Topics'][] = $json2;

最后出于性能原因(查看What is SELECT N+1?),您可能需要查看JOIN。总而言之:

$dbh = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$query = 'SELECT c.id AS chapter_id, c.chapterTitle, t.id as topic_id, t.topicArea FROM chapters c INNER JOIN topics t ON c.id = t.chapterid';
$json = array();
foreach ($dbh->query($query) as $row) {
  $json[$row['chapter_id']]['id'] = $row->chapter_id;
  $json[$row['chapter_id']]['chapter_title'] = $row->chapter_title;
  $json[$row['chapter_id']]['Topics'][] = array(
    'id' => $row->topic_id,
    'topicArea' => $row->topicArea,
  );
}
print json_encode(array_values($json));

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多