2017-02-27 139 views
-1

我有陣列命名的數據如下面PHP陣列組和創建多維關聯數組

$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"]) ; 
} 
+0

如果不是2ndyear,SEM1含有2個分支? IT和金融在multidim數組示例中? 鍵:$ data數組中的1和2。 –

+2

您的輸入和期望的輸出似乎不匹配。 – jeroen

+0

顯示關於所需數組合成的一些想法 –

回答

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

print_r($res); 
+0

它不會返回預期的o/p。它應該按考試分組,然後分組排列 – webpic