【问题标题】:Linked MySQL tables into PHP arrays将 MySQL 表链接到 PHP 数组中
【发布时间】:2016-07-09 15:14:36
【问题描述】:

我有两个表和一个链接(中间)表:

manufacturer                     car
+----+-----------+---------+     +----+----------+-------+
| id | make      | founded |     | id | model    | debut |
+----+-----------+---------+     +----+----------+-------+
| 1  | Ford      | 1903    |     | 1  | Model T  | 1908  |
| 2  | Chevrolet | 1911    |     | 2  | Series C | 1913  |
| 3  | Honda     | 1946    |     | 3  | Mustang  | 1962  |
|    |           |         |     | 4  | Camaro   | 1966  |
|    |           |         |     | 5  | Model G  | 1924  |
+----+-----------+---------+     +----+----------+-------+


manufacturer_car
+----+-----------------+--------+
| id | manufacturer_id | car_id |
+----+-----------------+--------+
| 1  | 1               | 1      |
| 2  | 2               | 2      |
| 3  | 1               | 3      |
| 4  | 2               | 4      |
+----+-----------------+--------+

注意:本田没有汽车。 Model G (Toyota) 不对应任何制造商。

我想在 PHP 中为这些链接表创建一个多维数组。汽车匹配将是制造商数组中的一个数组。我不确定如何在 PHP 中表示该类型的数组,以下是 JSON 表示:

[
  {
    "manufacturer": "Ford",
    "founded":      "1903",
    "cars":[
      {
        "model":    "Model T",
        "debut":  "1908"
      },
      {
        "model":    "Mustang",
        "debut":  "1962"
      }
    ]
  },
  {
    "manufacturer": "Chevrolet",
    "founded":      "1911",
    "cars":[
      {
        "model":    "Series C",
        "debut":  "1913"
      },
      {
        "model":    "Camaro",
        "debut":  "1966"
      }
    ]
  },
  {
    "manufacturer": "Honda",
    "founded":      "1946",
    "cars":[

    ]
  }
]

我试过了:

$query = "SELECT
            manufacturer.make,
            manufacturer.founded,
            car.model,
            car.debut
          FROM
            manufacturer
          LEFT JOIN manufacturer_car
            INNER JOIN car
            ON manufacturer_car.car_id = car.id
            ON manufacturer_car.manufacturer_id = manufacturer.id";

$rows = array();

if ($result = $connection->query($query)) {
  while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
  }
}

// Print array
print_r($rows);

但这会导致:

[0] => Array                |  [1] => Array
  (                         |    (
    [manufacturer] => Ford  |      [manufacturer] => Ford
    [founded] => 1903       |      [founded] => 1903
    [model] => Model T      |      [model] => Mustang
    [debut] => 1908         |      [debut] => 1962
  )                         |    )

我想,应该是这样的:

[0] => Array
  (
    [manufacturer] => Ford
    [founded] => 1903
    [cars] => Array
      (
        [0] => Array
          (
            [model] => Model T
            [debut] => 1908
          )
        [1] => Array
          (
            [model] => Mustang
            [debut] => 1962
          )
      )
  )

最终输出将是 JSON,就像上面的示例一样。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: php mysql json join multidimensional-array


    【解决方案1】:

    如果您将结果数组设为键为制造商的关联数组会更容易。

    但主要问题是您需要将汽车信息附加到制造商特定元素中数组元素的cars 元素中。

    $rows = array();
    while ($row = $row->fetch_assoc()) {
        if (!isset($rows[$row['make']])) {
            $rows[$row['make']] = array(
                'manufacturer' => $row['make'],
                'founded' => $row['founded'],
                'cars' => array()
            );
        }
        if ($row['model']) {
            $rows[$row['make']]['cars'][] = array(
                'model' => $row['model'],
                'debut' => $row['debut']
            );
        }
    }
    

    如果你想要一个索引数组而不是关联数组,你可以这样做:

    $rows = array_values($rows);
    

    在循环之后。

    【讨论】:

    • 谢谢你,巴尔玛。有几件事,如果我错了,请纠正我:1)$rows[$row['manufacturer']] 应该是$rows[$row['id']] 或另一个独特的行。 2) 最后的 if 语句 if ($row['model']) {} 创建一个与当前行分开的数组。
    • 1) 你的SELECT 中没有id,所以没有$row['id']。 2) 检查model 是否为NULL,这将发生在没有汽车的制造商身上,因此它不会在cars 中创建空条目。
    • 我不够清楚,我很抱歉。我已根据您的回答对问题进行了更新。
    • 是的,$row['manufacturer'] 是个错误,应该是 $row['make']。但是您问题中所需的输出是"car": "Series C", 而不是"model": "Series C"
    • $row['cars'][] 应该是 $rows[$row['make']]['cars'][]。我已经更正了答案。
    【解决方案2】:

    我相信由于 join 的工作方式,使用 sql 语句无法实现您想要的,但您可以像这样处理从查询中获得的信息:

    $manufacturer='';
    $actualRow=-1;
     while ($row = $result->fetch_assoc()) {
       if($manufacturer!==$row['manufacturer']){
         $rows[] = array('manufacturer'=>$row['manufacturer'],
                         'founded'=>$row['founded'],
                          'car'=>array($row['car']));
         $actualRow++;
       }else{
         $rows[$actualRow][car][]=$row['car'];
       }
     }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2013-03-17
      • 1970-01-01
      • 2016-08-24
      相关资源
      最近更新 更多