[英]PHP/MySQL Sort Multi-dimensional array
I'm trying to sort an array in to a three-deep array. 我正在尝试将一个数组排序为三个深度的数组。 This is my current query:
这是我当前的查询:
SELECT * FROM question
INNER JOIN category ON question.category_id = category.id
INNER JOIN difficulty ON question.difficulty_id = difficulty.id
Expected result is something like: 预期结果是这样的:
array(
'1' => array( // category id 1
'1' => array( // difficulty id 1
'1' => array('...'), // question id 1
'2' => array('...') // question id 2
),
'2' => array(
'3' => array('...'),
'4' => array('...')
)
)
)
I did have the following: 我确实有以下几点:
foreach($categories as $category) {
foreach($difficulties as $difficulty) {
foreach($questions as $question) {
if ($question['category_id'] == $category['id'] && $question['difficulty_id'] == $difficulty['id']) {
$feed[$category['id']][$difficulty['id']][$question['id']] = $question;
}
}
}
}
But there will be 10,000+ questions and performance will be bad so is there a way I can do this with one query and fewer loops? 但是会有10,000多个问题,性能会很差,所以有没有办法我可以用一个查询和更少的循环做到这一点?
Basically you could just return your query and order by the ids like so: 基本上,您可以按如下所示的ID返回查询和订单 :
Category_ID Difficulty_ID Question_ID
0 0 0
0 0 1
1 0 2
1 3 3
1 3 4
2 0 5
2 1 6
Then parse everything in a while: 然后在一段时间内解析所有内容:
load each row of each table like this: 像这样加载每个表的每一行:
key: unique table prefix + id value: columns (delimited with the delimiter defined before)
The easiest way to return a whole table at once is to define a second delimiter and then have some slightly ugly query in the form of: 一次返回整个表的最简单方法是定义第二个定界符,然后以以下形式进行一些难看的查询:
SELECT id||delimiter||col1||delimiter||...||colN FROM ...
And then put it all together with a list aggregation using the second delimiter ( group_concat()
in mysql). 然后使用第二个定界符(在mysql中为
group_concat()
将所有内容与列表聚合放在一起。
Sometimes you need maps (for N to M relations or also if you want to search questions by difficulty or category), but because each question only has one category and difficulty you are already done. 有时您需要地图(对于N对M关系,或者如果您想按难度或类别搜索问题),但是由于每个问题只有一个类别和难度,因此您已经完成了。
If the data is not too big and doesn't change after login, then you can just use the application cache and echo your stuff in script tags. 如果数据不是太大,并且在登录后不会更改,那么您可以使用应用程序缓存并在脚本标签中回显您的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.