Archie.bpgc
Archie.bpgc

Reputation: 24012

change indexes after array sorting

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.

Upvotes: 2

Views: 2820

Answers (1)

bitluni
bitluni

Reputation: 219

Use the key order with caution: when transferring JSON, Chrome will re-sort your indices, whereas Firefox will keep them intact. You can't be sure if the order is kept or not. The only way to solve this is to use

$array = array_values($ret)

or in your code change the last loop to

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

after your sort to create a clean ascending order. If you need the old index you have to store it within your data for each node.

Upvotes: 1

Related Questions