0

我有一个像这样的多维数组:

Array ( 

[0] => Array ( [ans_id] => 1 [ans_name] => PHP Hypertext Preprocessor [ques_id] => 1 [right_ans] => Yes [ques_name] => What is the acronym of PHP? [section_id] => 1 [section_name] => PHP ) 

[1] => Array ( [ans_id] => 2 [ans_name] => Preety Home Page [ques_id] => 1 [right_ans] => No [ques_name] => What is the acronym of PHP? [section_id] => 1 [section_name] => PHP ) 

[2] => Array ( [ans_id] => 3 [ans_name] => Programmed Hypertext Page [ques_id] => 1 [right_ans] => No [ques_name] => What is the acronym of PHP? [section_id] => 1 [section_name] => PHP ) 

[3] => Array ( [ans_id] => 4 [ans_name] => Programmed Hypertext Preprocessor [ques_id] => 1 [right_ans] => No [ques_name] => What is the acronym of PHP? [section_id] => 1 [section_name] => PHP ) ) 

我的桌子是这样的:

ans_id  ans_name                       ques_id                right_ans

1   PHP Hypertext Preprocessor           1                         Yes

2   Preety Home Page                     1                          No

3   Programmed Hypertext Page            1                          No

4   Programmed Hypertext Preprocessor    1                          No

5   Andy Suraski                        12                          No

6   Zeev Gutman                         12                          No

7   Rasmus Lerdorf                      12                         Yes

8   Perl                                12                          No

我想检索一组常见问题 id 的答案

即一组所有答案Ques_id='1',第二组所有答案ques_id='12',等等。

我应该使用这段代码:

foreach($all_ans_cat as $r)
{                       
   echo $r['ans_id']."  ".$r['ans_name']."<br>";
}

这是将表中存在的所有值作为一组检索,并在第二组中再次显示相同的值。

4

2 回答 2

0

您可以使用具有分组依据和聚合功能的查询

看一下

http://www.w3schools.com/sql/sql_groupby.asp

于 2012-10-25T10:45:27.377 回答
0

选择按 ques_id 排序的所有答案并生成所需结构的数组

$questions = array();
$prevQuestionId = null;
foreach ($all_ans_cat as $r) {
    if ($r['ques_id'] !== $prevQuestionId) {
        $questions[] = array(); 
    }
    $questions[sizeof($questions)-1][] = $r;
    $prevQuestionId = $r['ques_id'];
}

结果数组将是:

0:
    - [ans1, ques1]
    - [ans2, ques1]
    ...
1: 
    - [ans5, ques13]
    - [ans6, ques13]
    ...
...
于 2012-10-25T11:16:08.830 回答