duanbicheng3345 2011-11-27 21:09
浏览 83
已采纳

使用PHP和MySQL创建多维数组

I am new to PHP and am looking at efficient ways to return data from the database. Lets say I have a UserProfile table that has a one to many relationship with UserInterest and 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

An efficient way to retrieve data would be to create a multidimensional array such as:

$user = array(  "FirstName" => "John", 
                "LastName" => "Doe", 
                "Gender" => "Male", 
                "Interests" => array(
                    "Hiking", 
                    "Cooking"), 
                "Contact" => array(
                    "Email" => "john.doe@gmail.com", 
                    "Phone" => "(555) 555-5555"));

I can't seem to get my head around how this would be constructed in PHP. For simple data like interests I could use group_concat(i.Name) as Interests in the query to return interests back as a comma separated list in a single row, however, for an associative array such as Contact, I'd like to be able to get a handle on each key in the array using $user['Contact']['Email'].

From a "Best Practices" standpoint, I would assume that constructing an array like this in one query is a lot better than hitting the database multiple times to retrieve this data.

Thanks!

Neil

  • 写回答

3条回答 默认 最新

  • douweng1935 2011-11-27 21:20
    关注

    You can construct this array in one pass through the data returned by your query. In pseudo-code:

    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
    

    The syntax $user["Interests"][] = $data is valid PHP code. It is equivalent to array_push($user["Interests"], $data).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动