1

I have a sort function like this:

function aasort ($array, $key, $order) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    if($order == "asc")
        asort($sorter);
    else
        arsort($sorter);
    foreach ($sorter as $ii => $va){
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

To sort an array depending on 1 of the key values.

and the Array:

$mArray[]   = array(
    'id'  => $v->id,
    'count' => $v->count
);
aasort($mArray, 'count', 'desc');

And the data I get is:

"mArray":
    {
        "1":{"id":"80","count":"2"},
        "0":{"id":"77","count":"1"}
    }

Which I see in the developer tools, but when I copy it in some json editor and check, the problem is they come in the order of index

{
    "0":{"id":"77","count":"1"},
    "1":{"id":"80","count":"2"}
}

.done(function(d){
    for(var x in d.mArray){
      d.mArray[x];
    }
})

Here it takes in the index order which is again 0, 1, ... so the list comes as unsorted.

4

1 回答 1

0

谨慎使用键顺序:传输 JSON 时,Chrome 会重新排序您的索引,而 Firefox 会保持原样。您无法确定订单是否保留。解决这个问题的唯一方法是使用

$array = array_values($ret)

或在您的代码中将最后一个循环更改为

foreach ($sorter as $ii => $va)
    $ret[]=$array[$ii];

在您排序之后创建一个干净的升序。如果您需要旧索引,则必须将其存储在每个节点的数据中。

于 2013-08-10T19:19:37.680 回答