从三个表上的SQL查询PHP多数组(JSON)

时间:2017-10-16 23:58:52

标签: php mysql json rest multidimensional-array

我希望有人可以帮我解决这个具体问题。 我是PHP和MySQL的新手,但我尽我所能尽力而为。此外,我知道可能有类似的问题,但不幸的是,我尝试了我能想到的每个角度修改这些教程/答案以满足我的需要,但遗憾的是我已经失败了......

所以,这就是我的问题:我有3个MySQL表(联系人,电话号码和电话类型),用于简单的电话簿,结构如下:

|ID  |name  |          |ID  |cID  |tID  |number|          |ID  |type  |
-----------------------------------------------------------------------
 1    John              1    1     2     123456            1    Home
 2    Mary              2    2     1     234567            2    Mobile
 3    Sue               3    1     3     213234            3    Work
                        4    2     2     444321            
                        5    3     2     555543    

第一个表包含联系人姓名,第二个表包含号码详细信息,第三个表是"静态"用于引用电话号码类型的表。

现在,我在PHP中创建了一个简单的crud应用程序的api,并且我坚持创建数组,这将给我结果按照我设想的结构:

[
 {"ContactID": 1,
  "ContactName": "John",
  "PhoneNumbers": {
     "PhoneNumberID": 1,
     "PhoneType":     2,
     "PhoneNumber":   123456
     }
 },
 {...},
 {...}
]

我使用的查询是:

SELECT contacts.*, pt.type, pn.number, pn.id
FROM contacts
        LEFT JOIN phonenumbers pn ON c.ID = pn.cID
        LEFT JOIN phonetypes pt ON pn.tID = pt.ID

现在我坚持使用PHP语法来创建上面提到的数组。你能帮我指点正确的方向吗?

另外,由于这是一个演示CRUD功能的小作业,我对我的数据库不确定,三个表结构是否正常?我是否需要将其更改为其他内容?

提前致谢!干杯!

1 个答案:

答案 0 :(得分:1)

如果所有表都有ID列,则需要在SQL中使用别名来区分phonenumbers.idcontacts.id。因此,请将查询更改为:

SELECT contacts.*, pt.type, pn.number, pn.id AS phoneid
FROM contacts
LEFT JOIN phonenumbers pn ON c.ID = pn.cID
LEFT JOIN phonetypes pt ON pn.tID = pt.ID

以下是假设您正在使用PDO的代码; mysqli会是类似的。

$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) {
    if (!isset($result[$row['ContactID']]) {
        // If this is the first row for this contact, create an entry in the results
        $result[$row['ContactID']] = array(
            'ContactID' => $row['ID'],
            'ContactName' => $row['name'],
            'PhoneNumbers' => array()
        );
    }
    // Add this phone number to the `PhoneNumbers` array
    $result[$row['ContactID']]['PhoneNumbers'][] = array(
        'PhoneNumberID' => $row['phoneid'],
        'PhoneType' => $row['type'],
        'PhoneNumber' => $row['number']
    );
}
$result = array_values($result); // Convert from associative to indexed array
// Convert to JSON
echo json_encode($result);

生成的JSON将如下所示:

[
 {"ContactID": 1,
  "ContactName": "John",
  "PhoneNumbers": [
    {
     "PhoneNumberID": 1,
     "PhoneType":     "Mobile",
     "PhoneNumber":   "123456"
    },
    {
     "PhoneNumberID": 3,
     "PhoneType":     "Work",
     "PhoneNumber":   "213234"
    }
 },
 {...},
 {...}
]

PhoneNumbers是所有电话号码的数组,PhoneType是类型名称,而不是其ID。如果您只想要类型ID,则无需加入phonetypes