简体   繁体   English

将对象转换为数组,以便可以对其进行排序?

[英]Convert object to an array so i can sort it?

I have a object i that i list in HTML tables. 我有一个我在HTML表中列出的对象。 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. 然后在重新填充表格之前,我使用href链接调用sort函数对数组进行排序。

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? 简单的for循环怎么样?

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. data应该已经是数组。 You can verify this by checking the output from json_encode($data) : 您可以通过检查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: 但是, "name""type"实际上与它们似乎没有任何关联:

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

You can change that by keeping the mysql_fetch_assoc structure: 您可以通过保留mysql_fetch_assoc结构来更改它:

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

In theory, at least, the output to JavaScript would then be: 从理论上讲,至少,JavaScript的输出将是:

<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: 对于对象数组,可以使用sort方法按内部对象的值对data进行排序:

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") 示例: http : //jsfiddle.net/coiscir/GB2v3/1/ (尽管使用“ id”而不是“ 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/ 我的不如其他人好: http : //jsfiddle.net/andrewbriggs/xndMQ/4/

It could be done better but I'm not that good at javascript 可以做的更好,但是我的JavaScript不太好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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