mysql - sort calculation data to rank my data in php -
how can sort data give rate 5 stars, 4 stars, until 1 stars.
this query
function top5cust($tahun, $bulan) { if ($tahun == 'semua' && $bulan == 'semua'){ $data = $this->db->query("select nama_jalan, no_rumah, jarak, kelurahan, kecamatan, kota, count(*) freq t_cust group nama_jalan, no_rumah, jarak,kelurahan, kecamatan, kota order freq desc limit 5"); } else { $data = $this->db->query("select nama_jalan, no_rumah, jarak, kelurahan, kecamatan, kota, count(*) freq t_cust year(tgl_req) = $tahun , month(tgl_req) = $bulan group nama_jalan, no_rumah, jarak, jarak,kelurahan, kecamatan, kota order freq desc limit 5"); } return $data->result(); }
and php code
<table> <thead> <tr> <th><center>alamat</center></th> <th><center>jarak</center></th> <th><center>frekuensi</center></th> <th><center>rate</center></th> </tr> </thead> <tbody> <?php $cost=2000; $totalbeli=50000; foreach($top5cust $data){ $frekuensi=$data->freq; $jaraks=$data->jarak; $perhitunganrank=($frekuensi*$totalbeli)-($jaraks*$cost*$frekuensi); echo "<tr>"; echo "<td>".$data->nama_jalan." no ".$data->no_rumah.", ".$data->kelurahan.", ".$data->kecamatan.", ".$data->kota." </td>"; echo "<td>".$data->jarak."</td>"; echo "<td>".$data->freq."</td>"; echo '<td>'.$perhitunganrank.'</td>'; echo"</tr>"; }?> </tbody> </table>
how can sort data , give rate $perhitunganrank
without echo it. sorry if question not clear english not good.
regards, ridho
you can use usort
, can see documentation here: http://php.net/manual/en/function.usort.php example in case be:
$cost=2000; $totalbeli=50000; //we create empty array. need array because pdo resultsets iterable objects means can't iterate twice $my_array = array(); //now put objects empty array. each row resultset new object. foreach($top5cust $data){ // following shallow copy (using keyword 'clone'). ok long fields primitive variables. $my_object = clone $data; $my_object->perhitunganrank=($my_object->freq*$my_object->totalbeli)-($my_object->jarak*$cost*$my_object->freq); array_push($my_array, $my_object); } // need create function compares 2 objects , tells 1 comes first between two. // function used usort. // function compares using property perhitunganrank. function cmp($a, $b){ return strcmp($a->perhitunganrank, $b->perhitunganrank); } // sort based on function above usort($my_array, "cmp"); //finally print array of objects sorted. foreach($my_array $row_to_print){ $counter =1; echo "<tr>"; echo "<td>".$row_to_print->nama_jalan." no ".$row_to_print->no_rumah.", ".$row_to_print->kelurahan.", ".$row_to_print->kecamatan.", ".$row_to_print->kota." </td>"; echo "<td>".$row_to_print->jarak."</td>"; echo "<td>".$row_to_print->frekuensi."</td>"; echo '<td>'.$row_to_print->perhitunganrank.'</td>'; echo '<td>'.$counter.'</td>'; echo"</tr>"; $counter++; }
Comments
Post a Comment