我可能做错了,但我真的需要帮助掌握如何通过嵌套数组工作。我有两个表User和Reviews。
这是我正在使用的SELECT语句:
SELECT *
FROM `users`
LEFT JOIN `reviews`
ON users.userId = reviews.user_id
WHERE installation_id = $installation_id
这就是我接收数组的方式:
Array
(
[0] => Array
(
[userId] => 60
[usersEmail] => gggg@gmail.com
[password] => 0Vg+sLdlALchd39l+3K3QXFZlvh79bwqXFp/J3nIR+o=
[usersName] => Lauren
[role] => scout
[id] => 1
[user_id] => 60
[client_id] => 62
[comments] => This person was extremely professional and went above and beyond. Her pricing was reasonable.
[stars] => 4
)
[1] => Array
(
[userId] => 60
[usersEmail] => gggg@gmail.com
[password] => 0Vg+sLdlALchd39l+3K3QXFZlvh79bwqXFp/J3nIR+o=
[usersName] => Lauren Rothlisberger
[role] => scout
[id] => 2
[user_id] => 60
[client_id] => 1
[comments] => She was pretty good. I have a couple small complaints but overall decent experience.
[stars] => 3
)
[2] => Array
(
[userId] => 63
[usersEmail] => proth@mail.com
[password] =>
[usersName] => Paul Rothlisberger
[role] =>
[id] =>
[user_id] =>
[client_id] =>
[comments] =>
[stars] =>
)
)
关于这一点对我来说没有意义。我认为这更像是
[1] => Array
(
[userId] => 60
[usersEmail] => gggg@gmail.com
[password] => 0Vg+sLdlALchd39l+3K3QXFZlvh79bwqXFp/J3nIR+o=
[usersName] => Lauren Rothlisberger
[role] => scout
[id] => 2
[user_id] => 60
[client_id] => 1
Array [0](
[comments]
[stars] )
)
如何获得该阵列?此外,他们如何迭代用户然后向用户展示他们所有的评论和明星。
我也无法弄清楚如何找到UserId = 60的星星,然后给出该用户的平均星星。
感谢您提供给我的任何帮助。我显然缺少一些基础知识。请不要指向我通过它的文档,但不能应用它。
答案 0 :(得分:0)
因为您已经注意到所返回的每条记录都是完整记录,当涉及多对一关系时,您会获得每条记录的一条记录。
当我遇到这个时,我应用以下短循环来将结果打包成更类似于第二种格式的内容,但它包括每次重复用户级别字段。通过这种方式,我可以轻松计算每个用户的子项数,通过在输出端使用嵌套的foreach进行中间排序或其他操作。
$results = array();
$results_raw = db.select(' ... the select statement ');
if (is_array($results_raw)) foreach ($results_raw as $result) {
$results[$result['userId']] = $result;
}