jQuery asort() or keep sorting after JSON encoding?

561 Views Asked by At

I have a PHP array containing vehicle makes, like this :

array(
    5 => Audi,
    2 => Ford,
    1 => Opel,
    6 => Renault,
    9 => Volkswagen,
)

I get it with Ajax, returning JSON encoded array to my JS. Problem is, the json_encoding automatically sort my array by key, so I get :

array(
    1 => Opel,
    2 => Ford,
    5 => Audi,
    6 => Renault,
    9 => Volkswagen,
)

How can I keep my array sorted ? Or re-sort in jQuery ? Thank you

1

There are 1 best solutions below

3
Avijit On

Better you do it from PHP. Use sort() which doesn't maintain index association and then encode it as a JSON.

If possible you can return it as an associative array using mysqli_fetch_assoc(). So that it will look something like:

Array
(
    [0] => Array
        (
            [id] => 1
            [vehicle_makes] => Opel
        )

    [1] => Array
        (
            [id] => 2
            [vehicle_makes] => Audi
        )
    ...
)

Hope this will solve your problem.