简体   繁体   中英

Convert object to an array so i can sort it?

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>

How about a simple for loop?

var arr = [];
for (var key in data) {
    arr.push(data[key]);
}

Now sort this with a custom sort function (sorts by name in this case):

arr.sort(function(a, b) {
    if (a[0] == b[0]) {
        return 0;
    } else if (a[0] < b[0]) {
        return -1;
    } else {
        return 1;
    }
});

data should already be an array. You can verify this by checking the output from json_encode($data) :

<script>var data = [["foo",1],["bar",2],...];</script>

But, "name" and "type" don't really have any relevance with these, which you seem to want:

onclick="javascript:sort('name')"
onclick="javascript:sort('type')"

You can change that by keeping the mysql_fetch_assoc structure:

while($row = mysql_fetch_assoc($get)){
    $data[] = $row;
}

In theory, at least, the output to JavaScript would then be:

<script>var data = [{"name":"foo","id":1,"type":...},...];</script>

With an array of objects, you can use the sort method to sort data by the values of the inner objects:

function sort(key) {
    data = data.sort(function (a, b) {
        var A = a[key], B = b[key];

        if (A < B)
            return -1;
        if (A > B)
            return 1;

        return 0;
    });

    // ...
}

One way to update the table is to remove the old rows and append new (in place of the // ... above):

var table = document.getElementById('list');
var oldRows = [].slice.call(table.rows, 1); // 1 = skip the "header" row(s)

for (var r = 0, l = oldRows.length; r < l; r++) {
    oldRows[r].parentNode.removeChild(oldRows[r]);
}

for (var i = 0, l = data.length; i < l; i++) {
    table.innerHTML += '<tr><td>' + data[i].name + '</td><td>' + data[i].id + '</td></tr>';
}

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:

window.onload = function () {
    sort('name');
};

Mine is not as good as the others : http://jsfiddle.net/andrewbriggs/xndMQ/4/

It could be done better but I'm not that good at javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM