我是 PHP 的新手,正在寻找从数据库返回数据的有效方法。假设我有一个与 UserInterest 和 UserContact 具有一对多关系的 UserProfile 表:
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" => "john.doe@gmail.com",
"Phone" => "(555) 555-5555"));
我似乎无法理解如何用 PHP 构建它。对于兴趣之类的简单数据,我可以在查询中使用 group_concat(i.Name) 作为兴趣,以在单行中以逗号分隔列表的形式返回兴趣,但是,对于诸如联系人之类的关联数组,我希望能够使用 $user['Contact']['Email'] 获取数组中每个键的句柄。
从“最佳实践”的角度来看,我认为在一次查询中构建这样的数组比多次访问数据库以检索此数据要好得多。
谢谢!
尼尔
最佳答案
您可以一次通过查询返回的数据构造此数组。在伪代码中:
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)
。
关于php - 使用 PHP 和 MySQL 创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8289059/