PHP数组在循环中创建多维关联数组

时间:2017-02-27 12:49:31

标签: php multidimensional-array

我有数组命名数据如下

$data = array();
$data = array ( 
    [0] => Array (
                [class]         => 1styear 
                [branch]        => IT 
                [Exam]          => SEM1 
                [student name]  => Alex 
                [Bio]           => Good Boy
                 )
    [1] => Array ( 
                [class]         => 2ndyear 
                [branch]        => Finance 
                [Exam]          => SEM1 
                [student name]  => Mark
                [Bio]           => Intelligent 
                )
    [2] => Array (
                 [class]        => 2ndyear 
                 [branch]       => IT 
                 [Exam]         => SEM1 
                 [student name] => Shaun 
                 [Bio]          => Football Player
                  ) 
    [3] => Array ( 
                [class] => 1styear 
                [branch] => Finance 
                [Exam] => SEM2 
                [student name] => Mike 
                [Bio] => Sport Player 
                ) 
    [4] => Array ( 
                [class] => 1styear 
                [branch] => IT 
                [Exam] => SEM2 
                [student name] => Martin 
                [Bio] => Smart 
                 )
    [5] => Array ( 
                [class] => 1styear 
                [branch] => IT 
                [Exam] => SEM1 
                [student name] => Philip 
                [Bio] => Programmer
                  )
    ) 
课程,分支,考试可以重复 我需要对上面的元素进行分组并创建嵌套的多维关联数组。数组应该是这样的  预期o / p

array(
    '1styear' =>
        array (
            0 =>
                array(
                    'Exam' => 'SEM1',
                    'branch' =>
                        array (
                            0 => 'IT'
                        ),
                ),
            1 =>
                array(
                    'Exam' => 'SEM2',
                    'branch' =>
                        array (
                            0 => 'IT'
                        ),
                ),
        ),
    '2ndyear' =>
        array (
            0 =>
                array(
                    'Exam' => 'SEM1',
                    'branch' =>
                        array (
                            0 => 'Finance',
                        ),
                ),
            1 =>
                array(
                    'Exam' => 'SEM2',
                    'branch' =>
                        array (
                            0 => 'Finance'
                        ),
                )
        ),
)

在循环中我尝试了以下代码

foreach($data as $array){
    $rr[$array["class"]]['Exam'][$array["Exam"]][] = array("Competitors" =>$array["Competitor"]) ;
}

1 个答案:

答案 0 :(得分:0)

$res = [];
foreach ($data as $key => $val) {
    $res[$val['class']][] = ['Exam' => $val['Exam'],
                            'branch' => [$val['branch']]
      ]; 
}

print_r($res);