【问题标题】:Multiple MySQL table to json_encode多个 MySQL 表到 json_encode
【发布时间】:2013-01-22 15:01:47
【问题描述】:

我的数据库中有 3 个不同的表,分别名为 consoleConsole、consoleModel 和 consoleGame。然后我想要做的是每个控制台内部都有一个循环用于它的模型,每个模型内部都有另一个循环用于它的游戏,如下所示:

[
   {
      "Console":"PlayStation",
      "Information":[
         {
            "Model":"PlayStation 3",
            "Title":[
               {
                  "Game":"007 Legends",
                  "Publisher":"Electronic Arts"
               },
               {
                  "Game":"Ace Combat: Assault Horizon",
                  "Publisher":"Namco"
               }
            ]
         },
         {
            "Model":"PlayStation 2",
            "Title":[
               {
                  "Game":"007: Agent of Fire",
                  "Publisher":"Electronic Arts"
               },
               {
                  "Game":"Ace Combat 4: Shattered Skies",
                  "Publisher":"Namco"
               }
            ]
         },
         {
            "Model":"PlayStation 1",
            "Title":[
               {
                  "Game":"007 Racing",
                  "Publisher":"Electronic Arts"
               },
               {
                  "Game":"Ace Combat",
                  "Publisher":"Namco"
               }
            ]
         }
      ]
   },
   {
      "Console":"Wii",
      "Information":[
         {
            "Model":"Wii",
            "Title":[
               {
                  "Game":"007: Quantum of Solace",
                  "Publisher":"Activision"
               },
               {
                  "Game":"AC/DC Live: Rock Band Track Rack",
                  "Publisher":"MTV Games"
               }
            ]
         }
      ]
   },
   {
      "Console":"Xbox",
      "Information":[
         {
            "Model":"Xbox",
            "Title":[
               {
                  "Game":"AFL",
                  "Publisher":"Acclaim"
               },
               {
                  "Game":"American Chopper",
                  "Publisher":"Activision"
               }
            ]
         },
         {
            "Model":"Xbox 360",
            "Title":[
               {
                  "Game":"AFL Live",
                  "Publisher":"Electronic Arts"
               },
               {
                  "Game":"Akai Katana Shin",
                  "Publisher":"Cave"
               }
            ]
         }
      ]
   }
]

但遗憾的是,我并没有将我的数据库用于这个数据库,而是直接将它写在一个 php 文件中。

编辑

不管怎样,继续。我修改了我的代码,结果是这样的。

<?PHP
    $consoleQuery = "SELECT * ".
    "FROM consoleConsole ".
        "JOIN consoleModel ".
                "ON consoleConsole.consoleId = consoleModel.consoleId ".
            "JOIN consoleGame ".
                "ON consoleModel.modelId = consoleGame.gameId";

$consoleResult = mysql_query($consoleQuery);

$consoleFields = array_fill_keys(array(
    'consoleName',
    ), null);

$modelFields = array_fill_keys(array(
    'modelName',
    ), null);

$console = array();
$rowConsole = array();

while ($rowConsole = mysql_fetch_assoc($consoleResult)) {
    $consoleId = $rowConsole['consoleId'];
    $modelId = $row['modelId'];
    if (isset($console[$consoleId]['Information'])) {
        $console[$consoleId]['Information'][] = array_intersect_key($rowConsole, $modelFields);
    }

    else {
        $console[$consoleId] = array_intersect_key($rowConsole, $consoleFields);
        $console[$consoleId]['Information'] = array(array_intersect_key($rowConsole, $modelFields));
    }
}

$console = array_values($console);
echo json_encode($console);

?>

我能够产生一个输出,但它看起来不像上面的输出。

[
  {
    "consoleName": "PlayStation",
    "Information": [
      {
        "modelName": "PlayStation"
      },
      {
        "modelName": "PlayStation 2"
      },
      {
        "modelName": "PlayStation 3"
      },
      {
        "modelName": "PlayStation 3"
      }
    ]
  },
  {
    "consoleName": "Wii",
    "Information": [
      {
        "modelName": "Wii"
      },
      {
        "modelName": "Wii"
      }
    ]
  },
  {
    "consoleName": "Xbox",
    "Information": [
      {
        "modelName": "Xbox"
      },
      {
        "modelName": "Xbox 360"
      }
    ]
  }
]

他们的关系:

我现在的问题是,我无法添加每个游戏的标题。

【问题讨论】:

  • sql返回一个“平面”表,如果你想要更复杂的数据结构,你需要自己构建它
  • 是的,我想通了 :(

标签: php mysql join json


【解决方案1】:

好的,我已经编写了您的解决方案。您必须确保其中包含 order by,因为它假定您将它们与那里的物品一起订购。我也不知道您的发布者是如何存储的,所以我将其分离到一个单独的表中(这将允许您随后也可以通过那里的发布者获取项目),现在是 4 个连接。另外在另一个说明中,我也将其更新为进行内部连接。这样,对于没有分配任何游戏的控制台,您将不会得到空结果。如果你想要这些,你可以简单地改变连接,这样它也会给你这些结果。让我知道这是否有帮助

//get all of the information
$query = '
    SELECT c.consoleId,c.consoleName,m.modelId,m.modelName,g.gameId,g.gameName,p.publisherId,p.publisherName
    FROM `consoleconsole` c
        INNER JOIN `consolemodel` m ON c.consoleId=m.consoleId
        INNER JOIN `consolegame` g ON m.modelId=g.modelId
        INNER JOIN `consolepublisher` p ON g.publisherId = p.publisherId
    ORDER BY c.consoleName, m.modelName, g.gameName
';

//get the results
$result = mysql_query($query);

//setup array to hold information
$consoles = array();

//setup holders for the different types so that we can filter out the data
$consoleId = 0;
$modelId = 0;

//setup to hold our current index
$consoleIndex = -1;
$modelIndex = -1;

//go through the rows
while($row = mysql_fetch_assoc($result)){
    if($consoleId != $row['consoleId']){
        $consoleIndex++;
        $modelIndex = -1;
        $consoleId = $row['consoleId'];

        //add the console
        $consoles[$consoleIndex]['console'] = $row['consoleName'];

        //setup the information array
        $consoles[$consoleIndex]['information'] = array();
    }

    if($modelId != $row['modelId']){
        $modelIndex++;
        $modelId = $row['modelId'];

        //add the model to the console
        $consoles[$consoleIndex]['information'][$modelIndex]['model'] = $row['modelName'];

        //setup the title array
        $consoles[$consoleIndex]['information'][$modelIndex]['title'] = array();
    }

    //add the game to the current console and model
    $consoles[$consoleIndex]['information'][$modelIndex]['title'][] = array(
        'game'      => $row['gameName'],
        'publisher' => $row['publisherName']
    );
}

echo json_encode($consoles);

【讨论】:

  • while($row = mysql_fetch_assoc($result)) 给出Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given。对了,在INNER JOIN中$query,不就是consoleModel之类的吗?
  • 好吧,在尝试获取行之前,您应该始终进行一些错误检查。但基本上这意味着您的查询在这种情况下失败。您是否确保查询与您的表格对齐?我在“consolePublishers”中创建了那个额外的表,如果你没有它,它就会失败。您将需要创建该表或修改查询以提供您需要的信息。如果您想查看实际错误是什么,可以将查询行更改为“mysql_query($query) 或 die(mysql_error())”。
  • 是的,它是 consoleModel 等,但由于 mysql 不区分大小写(在大多数情况下),这并不重要,但您应该更新它以适合您的表结构。
  • 嗯,有一点问题。我已将 PlayStation Portable 添加到 consoleModel 并具有 modelId = 8 和 consoleId = 1。问题是,它没有显示在列表中。我还添加了 SN​​ES 到 consoleModel 有一个 consoleId = 5。
  • 是的,如果您的模型中没有任何游戏,我提供的代码不会给您返回结果。但是,如果您将“INNER JOIN”更改为“LEFT JOIN”,那么即使它们没有任何游戏,它也会为您提供控制台/模型。这完全取决于您要完成的工作。
【解决方案2】:

由于您使用 php 函数对 json 进行编码,它会以默认格式为您提供 json。您要做的是使用字符串操作创建自己的函数以获得所需的结果。

【讨论】:

  • 我会将字符串操作的结果放在json_encode 中,对吗?
  • 不,你不需要任何地方的 json_encode 只是一些 for 循环和一些字符串连接。
  • 但是输出仍然是 JSON 吗?
  • json 不是一种数据格式,而是一种具有父子关系的数据格式,并且可以具有多层这些关系。如果你可以通过 php 或 naything 获得这个结构并将你的文件保存为 .json 扩展名,那么你就得到了一个 json 文件。
猜你喜欢
  • 1970-01-01
  • 2015-06-08
  • 2013-04-27
  • 1970-01-01
  • 2015-11-25
  • 2015-10-20
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多