我希望有人能帮我解决这个具体问题。 我是 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功能的小作业,我不确定我的数据库,三表结构是否可以?我需要将其更改为其他内容吗?
提前致谢!干杯!
最佳答案
如果所有表都有 ID
列,您需要在 SQL 中使用别名来区分 phonenumbers.id
和 contacts.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
。
关于来自三个表的 SQL 查询的 PHP 多数组 (JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780602/