查询多个表MySQL不同大小的JSON输出

时间:2019-05-09 03:34:35

标签: php mysql json

为解释我的问题,我有3表有关饮料制造商的信息。它们类似于以下内容:

t_manufacturers
___________________________________
|   ID   |   name     |     phone  |
|    1   |   Coke     |    123456  |
|    2   |   Pepsi    |    654321  |
___________________________________
t_drinks
___________________________
|  ID   |        name      |
|   2   |   cherry Pepsi   |
|   1   |    cherry coke   |
___________________________
t_brandlogos
__________________________
|  ID  |     imagename    |
|   1  |   original_coke  |
|   2  |   original_pepsi |
|   2  |   cherry_pepsi   | 
|   1  |    cherry_coke   |
__________________________

我想查询该数据,以便获得一个json文件,其中包含每个制造商及其可用的所有品牌徽标/图像和饮料,并与表之间的ID相匹配。

如果我仅查询可乐信息,我会想象并希望'pretty'json读起来与此类似:

[
{
“ID”:1,
“name”:”coke”,
“drinks”: 
[{“name”:”cherry coke”},
  {“name”:”coke”}], 
“images”:
[{“imagename”:”original_coke”},
  {“imagename”:”cherry_coke”}]
]

我正在使用PHP从我的网站运行查询并返回json。我遇到的问题是我不确定如何编写MySQL查询逻辑以将结果获取到php中,以便php随后可以以json格式返回数据。

更清楚地说,我可以使其执行某些操作,但似乎无法获得查询/ php来正确构造出站json,并使用不包含重复信息的所有数据。

任何指导将不胜感激。

编辑***

我认为,这样做的方法是在PHP中运行3个查询,最后得到一系列饮料制造商及其饮料/图像的阵列(这是我想要的json输出所建议的)。

为此,我想我要查询饮料制造商的ID /名称,然后针对每个制造商分别查询其饮料/徽标阵列。

尽管php能够做到这一点...它像c ++一样简单。

结束编辑***

NEW EDITE ***

所以我确实设法将输出获取到数组数组,但是我现在遇到的问题是,而不是输出具有饮料/图像数组,如:

“drinks”: 
[{“name”:”cherry coke”},
  {“name”:”coke”}], 
“images”:
[{“imagename”:”original_coke”},
  {“imagename”:”cherry_coke”}]
]

相反,“饮料”和“图像”被替换为“ 0”和“ 1”。

到目前为止,我要完成的工作是查询所有制造商,然后为每个制造商使用ID查询所有饮料。我采用新的饮料阵列,然后将其附加到当前制造商阵列的末尾,对图像进行相同操作,然后将当前制造商添加到制造商阵列中。我使用以下smie-sudocode中的思想完成了这些循环:

for_each_manufacturer{
   for_each_drink{
        array_push($drinkArray, $tempDrinkArray);
   }
   array_push($currentManufacturerArray, $drinkArray);
   for_each_image{
        array_push($imageArray, $tempImageArray);
   }
   array_push($currentManufacturerArray, $imagesArray);
   array_push($manufacturerArray, $currentManufacturerArray);
}

我现在要解决的问题(因为我得到了正确的输出格式)是将“ 0”和“ 1”分别更改为“ drinks”和“ images”。

感谢到目前为止一直在帮助的每个人!

结束新编辑***

通过将旧数据的副本添加到数组中,但是使用了不同的键,然后将数据放在旧键下,我能够解决该问题。

$currentManufacturerArray["images"] = $currentManufacturerArray["1"];
            unset($currentManufacturerArray["1"]);

1 个答案:

答案 0 :(得分:0)

嗨,Charles,欢迎您使用Stack Overflow。

我建议将其分为三个不同的查询,首先是填写公司信息,其次是添加饮料,最后是添加图像。

当您不熟悉PHP时,这里有一些指导,指导您如何构建结果:

// define the response array
$responseArray = [];

// Step 1: fill in the companies, using the company ID as array key ("1" in the demo)
// replace this with your first mysqli_query();
// we will need the empty arrays later on.
$responseArray[1] = [
  'ID' => 1,
  'name' => 'Coca Cola',
  'drinks' => [],
  'images' => []
];

// Step 2: push in the drinks into the "drinks" sub-array, using the company ID and 'drinks' as array keys ("1" in the demo)
// this would happen in your second mysqli_query();
$responseArray[1]['drinks'][] = ['name' => 'Cherry Cola'];
$responseArray[1]['drinks'][] = ['name' => 'Coca cola Coke'];

// Step 2: push in the images into the "drinks" sub-array, using the company ID and 'images' as array keys ("1" in the demo)
// this would happen in your third mysqli_query();
$responseArray[1]['images'][] = ['imagename' => 'original_coke'];
$responseArray[1]['images'][] = ['imagename' => 'cherry_coke'];

// output the result as JSON. The array_values(...) call makes sure we won't have the company ID as array key in our result
header('Content-Type: application/json');
print json_encode(array_values($responseArray));

哪个会给您以下结果:

[
  {
    "ID": 1,
    "name": "Coca Cola",
    "drinks": [
      {
        "name": "Cherry Cola"
      },
      {
        "name": "Coca cola Coke"
      }
    ],
    "images": [
      {
        "imagename": "original_coke"
      },
      {
        "imagename": "cherry_coke"
      }
    ]
  }
]

要遍历company表并填写值,您将使用类似于以下代码:

// no error handling as this is just a functionality sample ...
$responseArray = [];
$connection = mysqli_connect('HOST', 'USER', 'PASS', 'DATABASE');

// add the companies ...
$query = '
    SELECT 
      ID, name 
    FROM 
      t_manufacturers';

$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
  $responseArray[$row['ID']] = [
    'id' => $row['ID'],
    'company' => $row['name'],
    'drinks' => [],
    'images' => []
  ];
}

这将为您提供包含所有公司的结果。如果您只想输出一个公司,请在三个查询中使用WHERE子句。在这个简单的演示中,您还可以使用以下方法从响应数组中选择一家公司:

print json_encode($responseArray[1]); // would give you the Coca section

让我知道这是否对您有帮助。