在PHP中循环遍历数组

时间:2013-05-10 08:23:09

标签: php

我创建了一个由部分和问题组成的数组。如何遍历各个部分并显示每个部分的嵌套问题。

以下是我创建数组的方法

$db = db_open();
$query = "SELECT * FROM assessment_selections WHERE assessment_id = '".$annual_assessment["id"]."' AND selection = '1' ORDER BY timestamp ASC";
$result = db_query($db, $query);
$result = db_fetch_all($result);
if (!is_array)
    $result = array();
foreach($result as $row) {
    $section[$row['section_id']][$row['question_id']] = $row;
}

这是数组

Array
(
    [1] => Array // Section 1
        (
            [1] => Array // Question 1
                (
                    [assessment_selection_id] => 70
                    [assessment_id] => 32
                    [section_id] => 1
                    [question_id] => 1
                    [selection] => 1
                    [timestamp] => 1368172762
                )

        )

    [2] => Array // Section 2
        (
            [3] => Array // Question 3
                (
                    [assessment_selection_id] => 68
                    [assessment_id] => 32
                    [section_id] => 2
                    [question_id] => 3
                    [selection] => 1
                    [timestamp] => 1368166250
                )

        )

    [3] => Array // Section 3
        (
            [4] => Array // Question 4
                (
                    [assessment_selection_id] => 69
                    [assessment_id] => 32
                    [section_id] => 3
                    [question_id] => 4
                    [selection] => 1
                    [timestamp] => 1368172690
                )

        )

    [4] => Array // Section 4
        (
            [5] => Array // Question 5
                (
                    [assessment_selection_id] => 71
                    [assessment_id] => 32
                    [section_id] => 4
                    [question_id] => 5
                    [selection] => 1
                    [timestamp] => 1368174153
                )

        )

)



预期结果(我希望能够在PHP中回显它们)

第1节

  • 问题1
  • 问题4
  • 问题7

第2节

  • 问题2
  • 问题9

第3节

  • 问题3

3 个答案:

答案 0 :(得分:2)

再次使用foreach

foreach ( $data as $n => $sect) {
    echo "Section $n<br>";
    foreach ($sect as $q => $qdata) {
        echo " -> Question $q<br>";
        // ... do something
    }
}

答案 1 :(得分:2)

你应该使用这个循环。

foreach($section as $k=>$section)
{
   echo "section $k";
   foreach($section as $i=>$question)
   {
     echo "question $i ".$question['assessment_id']; //more fields available here
   }
}

答案 2 :(得分:1)

foreach($section as $key => $value) {
    echo "Section ".$key;
    foreach($value as $key => $value) {
        echo "Question ".$key;
    }
}