2017-10-16 114 views
2

我希望有人能夠幫助我解決這個特定的問題。 我是PHP和MySQL的新手,但我盡我所能。此外,我知道可能類似的問題已被問到,但不幸的是,我嘗試了每個角度,我可以想到修改這些教程/答案,以滿足我的需求,但不幸的是我已經失敗悲慘..來自三個表上的SQL查詢的PHP多數組(JSON)

所以,這是我的問題:我有一個簡單的電話簿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功能,所以我不確定我的數據庫是三表結構嗎?我需要改變它到別的嗎?

在此先感謝!乾杯!

+0

不應該'PhoneNumbers:'是一個對象數組,而不是一個單一的對象? – Barmar

+0

糟糕,你是對的。可能我應該去睡覺,因爲我已經沒有用了。現在是凌晨2點半這裏..晚安好人,我希望明天會比今天好... – cobster

回答

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

+0

謝謝@Barmar!正是我在尋找的東西,像魅力一樣工作! – cobster