加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用PHP和MySQL创建多维数组

发布时间:2020-12-13 22:32:53 所属栏目:PHP教程 来源:网络整理
导读:我是 PHP的新手,正在寻找从数据库返回数据的有效方法.假设我有一个UserProfile表,它与UserInterest和UserContact有一对多的关系: Select p.Id,p.FirstName,p.LastName,i.Name as Interests,c.Email,c.Phonefrom UserProfile pleft join UserInterest i on p
我是 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" => "john.doe@gmail.com","Phone" => "(555) 555-5555"));

我似乎无法理解如何在PHP中构建它.对于像兴趣这样的简单数据,我可以在查询中使用group_concat(i.Name)作为Interests将兴趣作为逗号分隔的列表返回到单行中,但是,对于像Contact这样的关联数组,我希望能够使用$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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读