2017-04-02 89 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 –