有没有办法运行一个 mysql查询并获取多维数组?
例如,假设您有一个特定用户,并且您想要获取该用户的数据以及该用户的最新事件/活动。
表结构类似于:
users
表:
ID | username | emailaddress | firstname | lastname | dateofbirth
events
表:
ID | user | event_label | timestamp
当然只能有一个唯一身份用户,但该用户可以有多个事件。因此,如果我在这两个表上执行LEFT JOIN
,我将不得不使用while循环来获取所有事件行。但是在每次迭代中,我将再次从users
表中获得相同的数据。
例如,查询的代码可能是这样的:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$id = 123456;
$select = $mysqli->query("
SELECT users.*, events.event_label, events.timestamp
FROM users
LEFT JOIN events ON users.id=events.user
WHERE users.id=$id
");
while ($row = $select->fetch_assoc()) {
$result[] = $row;
}
echo "<pre>";
print_r($result);
exit("</pre>");
/*
Sample output:
Array (
[0] => Array
(
[id] => 1
[username] => name
[emailaddress] => joe@example.com
[firstname] => Joe
[lastname] => Test
[dateofbirth] => 2015-07-10
[event_label] => Subscribe
[timestamp] => 2015-07-10 00:00:00
)
[1] => Array
(
[id] => 1
[username] => name
[emailaddress] => joe@example.com
[firstname] => Joe
[lastname] => Test
[dateofbirth] => 2015-07-10
[event_label] => Visit
[timestamp] => 2015-07-10 01:00:00
)
[2] => Array
(
[id] => 1
[username] => name
[emailaddress] => joe@example.com
[firstname] => Joe
[lastname] => Test
[dateofbirth] => 2015-07-10
[event_label] => phonecall
[timestamp] => 2015-07-10 03:00:00
)
)
*/
期望的结果将如下所示。我知道我可以在PHP中重新排列数据,但我想知道是否可以用MySQL实现相同的目标。
/*
Desired output:
Array (
[0] => Array (
[id] => 1
[username] => name
[emailaddress] => joe@example.com
[firstname] => Joe
[lastname] => Test
[dateofbirth] => 2015-07-10
[events] => Array (
[0] => Array (
[event_label] => Subscribe
[timestamp] => 2015-07-10 00:00:00
)
[1] => Array (
[event_label] => Visit
[timestamp] => 2015-07-10 01:00:00
)
[2] => Array (
[event_label] => phonecall
[timestamp] => 2015-07-10 03:00:00
)
)
)
*/
答案 0 :(得分:2)
您应该可以稍微更改Select
声明,以便于处理:
$select = $mysqli->query("
SELECT users.username,
users.emailaddress,
users.firstname,
users.lastname,
users.dateofbirth,
events.event_label,
events.timestamp
FROM users
LEFT JOIN events ON users.id=events.user
WHERE users.id=$id
");
然后修改你的while
循环,这样你就可以在php中获取一个多维数组
while ($row = $select->fetch_assoc()) {
$result[[$row['id']] = $row;
}