2017-04-02 69 views
1

嗨格式化我有一个PHP数组这样PHP交叉从阵列

$table=array(); 
$subject_names=array(); 

$subject_names[118]="English"; 
$subject_names[108]="Software Engeneering"; 

$table['Josh'][118]['int'] =55; 
$table['Josh'][118]['ext'] = 10; 
$table['Josh'][108]['int'] =45; 
$table['Josh'][108]['ext'] = 12; 

$table['Matt'][118]['int'] =45; 
$table['Matt'][118]['ext'] = 12; 
$table['Matt'][108]['int'] =50; 
$table['Matt'][108]['ext'] = 15; 

这里118和108 subject_id我想这样

student |  English   | Software Engeneering | 
      | int. mark | ext. mark | int. mark | ext. mark | 
    ___________________________________________________________ 
    Josh | 55  | 10   | 45  | 12 
    Matt | 45  | 12   | 50  | 15 

我试图

echo "Student Name\t"; 

foreach($subject_names as $sub_name) 
{ 
    echo "$sub_name\t"; 
} 
echo "<br>";  

foreach($table as $sname => $subjects){ 

    echo "$sname\t"; 

    foreach($subjects as $subject_name => $types) 
    { 
     foreach($types as $marks) 
     { 
      echo "$marks\t"; 
     } 
    } 
    echo "<br>"; 

} 
进行格式化

它工作正常,但如果我改变表的数组项目的位置,如

$table['Josh'][118]['int'] =55; 
$table['Josh'][108]['int'] =45; 
$table['Josh'][118]['ext'] = 10; 
$table['Josh'][108]['ext'] = 12; 

它不会给出正确的结果。无论如何要确保结果总是正确的。

感谢您的帮助和建议

+0

我会假设你**不是**默认情况下硬编码这些值,而是从数据库中拉出来?你在这里遇到的问题是你的代码期望一切都是完美的。如果您预期的东西不按顺序排列,您需要先排序。如果您希望发生这种情况,那么如果您需要,我会很乐意提供更多帮助。 – Augwa

+0

是的,我正在从数据库中提取这些值。我将不胜感激您的任何帮助。 – sanu

+0

好的,所以你只需要确保你正确地对你的数据库值进行排序......即'ORDER BY student,class_id,mark_type' – Augwa

回答

0

这里有一个解决方案,我写了你的要求,选择使用$subject_names的控制,而不是学生记录表(我希望你明白我的贯通进入后平均得分代码)...

$table=array(); 
$subject_names=array(); 

// notice that I switched subject order, just to show that subjects control the marks displayed thereby ensuring consistent score mapping 
$subject_names[108]="Software Engeneering"; 
$subject_names[118]="English"; 

// and I'm using the rearranged scores (the sample use-case you specified in the question that distorts your output) 
$table['Josh'][118]['int'] =55; 
$table['Josh'][108]['int'] =45; 
$table['Josh'][118]['ext'] = 10; 
$table['Josh'][108]['ext'] = 12; 

$table['Matt'][118]['int'] =45; 
$table['Matt'][118]['ext'] = 12; 
$table['Matt'][108]['int'] =50; 
$table['Matt'][108]['ext'] = 15; 

echo "Student Name\t"; 

foreach($subject_names as $sub_name) 
{ 
    echo "$sub_name\t"; 
} 
echo "\n"; 

// proposed solution: 
foreach($table as $sname => $subjects){ 

    echo "$sname\t"; 

    foreach ($subject_names as $subject_id => $name) { 

     foreach ($subjects[$subject_id] as $mark) { 
      echo "$mark\t"; 
     } 
    } 
    echo "\n"; 

} 

这里是上面的脚本输出...

Student Name Software Engeneering English 
Josh 45 12 55 10 
Matt 50 15 45 12 

通过脚本运行的相同数据在这个问题提供,这里的输出(失真)...

Student Name Software Engeneering English 
Josh 55 10 45 12 
Matt 45 12 50 15 

P.S: 'Engeneering' 应该是 '工程'

我希望我已经帮助。 干杯!

+0

纠正他的数据顺序并不能帮助他。问题在于数据何时出现故障。 – Augwa

+0

请阅读代码...我重新安排了数据,以显示我的算法不受数据顺序影响,没有*正确* –

+0

不好意见downvote你不明白@Augwa –