php - 使用 PHP 和 MySQL 创建多维数组

标签 php

我是 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/

相关文章:

php - 获取 Woocommerce 文件中当前产品类别的子类别

php - 在 php 中获取 url 内容的安全性

php - 无法选择表并同时向其中插入内容(Mysql)

java - PHP 没有返回预期的结果

php - 从 mysql 更改为 mysqli

php - 如何从我的网站发送短信?只需要发送短信,不需要接收

php - 使用 MySQL 在一个查询中获取关注者和关注

php - Facebook API - 上传图片后获取图片 URL

php - 如何在字符串上使用 PHP rot13?

php - 根据 PHP 中包含的文件更改标题