I have a object i that i list in HTML tables. But i want to able to click different columns in this table to “sort” the the data based on that field in question.
As I’m aware of objects are not sorted, so i need to convert it to an array some how ? And then i use href links to call a sort function to sort the array before repopulating the table.
Was hopeing some one may be able to shed light to explain how i do it ?
This is basically how far i got:
$get = mysql_query("SELECT * FROM game_buildings") or die(mysql_error());
$i = 0;
while($row = mysql_fetch_assoc($get)){
$data[$i][0] = $row['name'];
$data[$i][1] = $row['id'];
$i ++;
}
$data = json_encode($data);
?>
<script>var data = <?echo $data; ?>; </script>
Then the table:
<table id="list" style="width:70%;margin: 0 auto;" border="1">
<tr>
<td align="center">
<a href="#" onclick='javascript:sort('name')'>Name</a>
</td>
<td align="center">
<a href="#" onclick='javascript:sort('type')'>Type</a>
</td>
</tr>
<script>
for(var key in data){
result += '<tr><td>'+data[key][0]+'</td><td>'+data[key][1]+'</td></tr>';
}
document.getElementById('list').innerHTML += result;
</script>
</table>
datashould already be an array. You can verify this by checking the output fromjson_encode($data):But,
"name"and"type"don’t really have any relevance with these, which you seem to want:You can change that by keeping the
mysql_fetch_assocstructure:In theory, at least, the output to JavaScript would then be:
With an array of objects, you can use the
sortmethod to sortdataby the values of the inner objects:One way to update the table is to remove the old rows and append new (in place of the
// ...above):Example: http://jsfiddle.net/coiscir/GB2v3/1/ (albeit, using “id” rather than “type”)
With this, you can take the initial loop out of the markup as well: