| re: Problem of sorting table
wow that's some ugly code!
try this:
<?php
function insert_datatable_cmp ($a, $b) {
$column = $_GET['sort'];
return ($a[$column]<$b[$column]) ? -1 : 1;
}
function insert_datatable($data,$columns,$sortable = array(),$caption =
'My Caption')
{
echo "<h2>$caption</h2>";
if(isset($_GET['sort'])) {
usort($data,"insert_datatable_cmp");
}
echo '
<table>
<thead>';
foreach ($columns as $column => $type)
{
if (in_array($column,$sortable))
{
echo str_replace('$column',$column,'<th><a
href="?sort=$column">$column</a></th>');
}else{
echo "<th>$column</th>";
}
}
echo '
</thead>
<tbody>';
foreach ($data as $row)
{
echo '<tr>';
foreach ($row as $col => $item)
{
$type = $columns[$col];
switch ($type)
{
case 'link':
echo str_replace('$item',$item,'<td><a
href="$item">$item</a></td>');
break;
case 'text':
default:
echo "<td>$item</td>";
}
}
echo '</tr>';
}
echo '
</tbody>
</table>';
}
$data = array();
$data[0]['name'] = 'A';
$data[0]['size'] = 3;
$data[0]['length'] = 5;
$data[0]['0min'] = 1;
$data[0]['3min'] = 10;
$data[0]['10min'] = 3;
$data[0]['chart'] = 'fig1.jpg';
$data[1]['name'] = 'B';
$data[1]['size'] = 5;
$data[1]['length'] = 2;
$data[1]['0min'] =2;
$data[1]['3min'] = 4;
$data[1]['10min'] = 3;
$data[1]['chart'] = 'figB.jpg';
$data[2]['name'] = 'C';
$data[2]['size'] = 4;
$data[2]['length'] = 3;
$data[2]['0min'] = 3;
$data[2]['3min'] = 9;
$data[2]['10min'] = 6;
$data[2]['chart'] = 'figC.jpg';
$columns = array();
$columns['name'] = 'text';
$columns['size'] = 'text';
$columns['length'] = 'text';
$columns['0min'] = 'text';
$columns['3min'] = 'text';
$columns['10min'] = 'text';
$columns['chart'] = 'link';
$sortable = explode(',','name,size,length');
insert_datatable($data,$columns,$sortable,'My Own Caption');
?> |