我是 PHP 新手,正在寻找从数据库返回数据的有效方法。假设我有一个 UserProfile 表,它与 UserInterest 和 UserContact 具有一对多关系:
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] /cdn-cgi/l/email-protection",
"Phone" => "(555) 555-5555"));
我似乎无法理解如何用 PHP 构建它。对于像兴趣这样的简单数据,我可以在查询中使用 group_concat(i.Name) 作为兴趣,以将兴趣作为单行中的逗号分隔列表返回,但是,对于诸如联系人之类的关联数组,我希望能够使用 $user['Contact']['Email'] 获取数组中每个键的句柄。
从“最佳实践”的角度来看,我认为在一个查询中构建这样的数组比多次访问数据库来检索该数据要好得多。
Thanks!
Neil