将ROWS分组为具有相同标识符的数组

Chr*_*age 2 php

如何在foreach循环内部运行此数组并将共享相同的行组合在一起section_id

我用注释块标记了所有行和部分.

这是阵列

Array ( 
    [0] => Array ( // Row 1
        [assessment_selection_id] => 63 
        [assessment_id] => 32 
        [section_id] => 1 // Section 1
        [question_id] => 1 
        [selection] => 2 
        [timestamp] => 1368160586 
   ) 
   [1] => Array ( // Row 2
        [assessment_selection_id] => 61 
        [assessment_id] => 32 
        [section_id] => 2 // Section 2
        [question_id] => 1 
        [selection] => 3 
        [timestamp] => 1368160510 
   )
   [2] => Array ( // Row 3
        [assessment_selection_id] => 61 
        [assessment_id] => 32 
        [section_id] => 2 // Section 2
        [question_id] => 1 
        [selection] => 3 
        [timestamp] => 1368160510 
   ) 

   [3] => Array ( // Row 4
        [assessment_selection_id] => 61 
        [assessment_id] => 32 
        [section_id] => 2 // Section 2
        [question_id] => 1 
        [selection] => 3 
        [timestamp] => 1368160510 
   ) 
)
Run Code Online (Sandbox Code Playgroud)


预期结果

Array ( 
   [0] => Array ( // Section 1
        [0] => Array ( // Row 1 
            [assessment_selection_id] => 63 
            [assessment_id] => 32 
            [section_id] => 1 
            [question_id] => 1 
            [selection] => 2 
            [timestamp] => 1368160586 
        )
    )
    [1] => Array ( // Section 2
        [0] => Array ( // Row 1
            [assessment_selection_id] => 61 
            [assessment_id] => 32 
            [section_id] => 2 
            [question_id] => 1 
            [selection] => 2 
            [timestamp] => 1368160586 
        )
       [1] => Array ( // Row 2
            [assessment_selection_id] => 61 
            [assessment_id] => 32 
            [section_id] => 2 
            [question_id] => 1 
            [selection] => 2 
            [timestamp] => 1368160586 
        )
       [2] => Array ( // Row 3
            [assessment_selection_id] => 61 
            [assessment_id] => 32 
            [section_id] => 2 
            [question_id] => 1 
            [selection] => 2 
            [timestamp] => 1368160586 
        )
    )
)
Run Code Online (Sandbox Code Playgroud)


没有数组的预期结果

第1节

  • 第1行

    assessment_selection_id,assessment_id,section_id,question_id,selection,timestamp

第2节

  • 第1行

    assessment_selection_id,assessment_id,section_id,question_id,selection,timestamp

  • 第2行

    assessment_selection_id,assessment_id,section_id,question_id,selection,timestamp

  • 第3行

    assessment_selection_id,assessment_id,section_id,question_id,selection,timestamp

SAV*_*AFA 5

让我们认为你的数组保存在$ myArray中这样做:

$newArray=array();
foreach($myArray as $val){
    $newKey=$val['section_id'];
    $newArray[$newKey][]=$val
}
print_r($newArray);
Run Code Online (Sandbox Code Playgroud)