[英]PHP multi array (JSON) from SQL query on three tables
我希望有人可以幫助我解決這個特定問題。 我是 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
加入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.