2011-11-27 65 views
4

多維數組我是新來的PHP,並期待在有效的方法來從數據庫返回數據。比方說,我有了一個與使用者興趣和UserContact許多關係的用戶配置表:創建PHP和MySQL

Select p.Id, p.FirstName, p.LastName, i.Name as Interests, c.Email, c.Phone 
from UserProfile p 
left join UserInterest i on p.Id = i.UserProfileId 
left join UserContact c on p.Id = c.UserProfileId 
where p.Id = 1 

一種有效的方法來檢索數據是創建一個多維數組,例如:

$user = array( "FirstName" => "John", 
       "LastName" => "Doe", 
       "Gender" => "Male", 
       "Interests" => array(
        "Hiking", 
        "Cooking"), 
       "Contact" => array(
        "Email" => "[email protected]", 
        "Phone" => "(555) 555-5555")); 

我似乎無法讓我的頭在PHP中如何構建。對於像我可以使用GROUP_CONCAT(i.Name)的興趣在查詢返回的興趣回爲一個逗號相隔一行列表,但是,對於關聯數組,如聯繫的利益簡單的數據,我想能夠使用$ user ['Contact'] ['Email']獲得數組中每個鍵的句柄。

從「最佳實踐」的角度來看,我認爲在一個查詢構建一個這樣的數組比多次進入數據庫檢索這些數據要好很多。

謝謝!

尼爾

+1

如果你正在尋找最好的做法,你應該看看PDO(http://www.php.net/pdo)。 –

+0

'UserInterest's是真正看起來是一個對許多人來說,如果'UserContact'只引用每用戶一行的唯一部分。如果是這樣的話,你將需要獲得'UserInterest's在另一個查詢,或者可能使用子查詢並連接所有的利益結果到一個字段中第一個查詢。 –

回答

1

你可以通過你的查詢返回的數據構建這個陣列中的一個通行證。在僞代碼中:

for each row 
    $user["FirstName"] = row->FirstName; 
    $user["LastName"] = row->LastName; 
    $user["Interests"][] = row->Interests; 
    $user["Contact"]["Email"] = row->Email; 
    $user["Contact"]["Phone"] = row->Phone; 
next 

語法$user["Interests"][] = $data是有效的PHP代碼。它相當於array_push($user["Interests"], $data)

0

我的猜測是,你必須運行單獨的查詢和手動構建自己的數組。我個人不知道PHP中的任何MySQL數據庫資源會按照您所描述的方式返回多維數組中的行集。

0

這樣做可能是一個更好的辦法:

$query = "SELECT p.Id, p.FirstName, p.LastName, i.Name as Interests, 
      c.Email, c.Phone 
      FROM UserProfile p 
      LEFT JOIN UserInterest i ON p.Id = i.UserProfileId 
      LEFT JOIN UserContact c ON p.Id = c.UserProfileId 
      WHERE p.Id = 1"; 

$res = GIDb::pg_query($query); 

if(pg_num_rows($res) > 0) 
{ 
    while($data = pg_fetch_assoc($res)) 
    { 
     $id = $data['Id']; 
     $f_name = $data['FirstName']; 
     $l_name = $data['LastName']; 
     $interests = $data['Interests']; 
     $email = $data['Email']; 
     $phone = $data['Phone']; 
    } 
} 

//You can also directly use $data['Id'] etc. 

也不要忘記在PHP代碼的開頭,包括:include_once(dirname(__FILE__)."/../../class.GIDb.php");

編輯:
這是Postgres的。
對於MySQL使用:mysql_query(), mysql_fetch_assoc(), mysql_num_rows()