2017-08-03 17 views
-2

這是我的代碼:排序表的最後一列的值,它是一個計算的變量


<? 

$i=0; 

foreach ($data as $key => $value) 
{ 

?> 
    <tr> 
     <td><?=number_format($value[budget],0)?></td> 
     <td><?=number_format($value[htd],0)?></td> 
     <td><?=number_format($value[etc],0)?></td> 
     <td><? 

     $per=number_format(($value[htd]+$value[etc])/$value[budget],2); 

     echo $per; 

     ?></td> 
    </tr> 
<?$i++;}?> 

所以,每$是一個計算值,我想按照這個數字排序我的表格。我可以得到一些幫助嗎?

+0

這與您所要求的內容無關,但需要引用數組鍵。它應該是'$ value ['budget']'等。 –

+0

這個數據來自哪裏?數據庫表?這是做排序和計算的適當場所。 – mickmackusa

+0

謝謝@ Don'tPanic。 – Lakito

回答

1

您只能使用數據,一旦你擁有了它,所以:

//add what you want first 
foreach($data as $key => $value){ 
    $data[$key]['per'] = ($value['htd'] + $value['etc'])/$value['budget']; 
} 

//then sort 
usort($data, function($a, $b){ 
    return $a['per'] == $b['per'] ? 0 : ($a['per'] > $b['per'] ? 1 : -1); 
}); 

//then display the data 
foreach($data as $key => $value){ 
?> 
    <tr> 
    <td><? echo number_format($value['budget'],0); ?></td> 
    <td><? echo number_format($value['htd'],0); ?></td> 
    <td><? echo number_format($value['etc'],0); ?></td> 
    <td><? echo number_format($value['per'],2); ?></td> 
    </tr> 
<? 
} 
+0

@ Don'tPanic你是對的。我修好了它。感謝您的注意。 –

+1

沒問題:)還有一點需要注意的是,如果可以使用PHP 7,那麼組合比較運算符會使它更整潔。 ('$ a ['per'] <=> $ b ['per']') –

相關問題