按键名称对数组进行分组。 [Keyname取决于用户的输入]

时间:2014-02-11 01:50:43

标签: php mysql arrays

这是我生成数组的代码

$query = "SELECT GROUP_CONCAT(distinct SubCode ORDER BY SubCode SEPARATOR ' ')as           
SubCode,GROUP_CONCAT(grade ORDER BY SubCode SEPARATOR ' ')as grade FROM VMESubjectGrade      
where ProgCode='$a' and Sessi='$b' and Intake='$c' GROUP BY matricNo";

$cols = "SELECT GROUP_CONCAT(distinct SubCode ORDER BY SubCode SEPARATOR ' ')as   
SubCode,sub_id FROM VMESubjectGrade where ProgCode='$a' and Sessi='$b' and 
Intake='$c' order by SubCode" ;


$result = mysql_query($cols); 


$gradee = mysql_query($query);


while ($row1 = mysql_fetch_assoc($result))

{  $pixx =explode(" ", $row1['SubCode']);

} 


while($row = mysql_fetch_array($gradee))

{
$pieces =explode(" ", $row['SubCode']);
$comps = array_intersect($pixx, $pieces);
$pi =explode(" ", $row['grade']);
$conbi = array_combine ($comps ,$pi );

//print_r($conbi);

echo array2table($conbi);
 }
`array2table` is a function that produce table for any array

这是我的数组

conbi = 

Array ( [MMB617] => I )

Array ( [MBP633] => B+ [MMB617] => C- [MQM613] => A- )

Array ( [MCT654] => A- [MMB617] => B- [MTH651] => B+ )

Array ( [MPP799] => A- ) 

Array ( [MMB617] => I [MMD634] => I [MQM613] => I ) 

Array ( [MBP633] => A- [MVF632] => A ) Array ( [MPP799] => B ) 

Array ( [MMB617] => I [MQM613] => I )

当我按表输出时,它看起来像这样

MMB617
I
MBP633         MMB617           MQM613
B+              C-                  A-
MCT654         MMB617           MTH651
A-               B-                 B+
MPP799
A-
MMB617         MMD634            MQM613
 I               I                I
MBP633         MVF632
 A-              A
MPP799
 B
MMB617         MQM613
 I               I

我希望我的数组按主题分组,以便所有主题都是标题,我的表格看起来像这样

MBP633  MCT654  MMB617  MMD634  MPP799  MQM613  MTH651  MVF632
                    I
B+                  C-                       A-
            A-      B-                             B+
                            A-
                    I       I                I
A-                                                        A
                                    B
                    I                        I

1 个答案:

答案 0 :(得分:0)

你的问题不清楚,你的代码也是如此。试试这个

$ordered = array()
foreach ($conbi as $arrays) {
    foreach($arrays as $key=>$value){
       if(!array_key_exists($key, $ordered){$ordered[$key] = array();}
       array_push($ordered[$key], $value);
    }
}

print_r($ordered);

为了得到好的或任何答案,你最好提出明确的问题。环顾四周,看看好的例子。