JSON response to client is taking ascending order by default

I have prepared an array in php with descending order, converted into json_encode. But in client side, I am getting output in ascending order.

Can anyone please help me how can I send with descending order to client.

Array is like

Array('code' => '1', 'data' => Array('10' => "Test1", '3' => 'Test2', '1' => 'Test3'))

and JSON Output is like

{'code' : '1', 'data' : {'1' : 'Test3', '3' : 'Test2', '10' : 'Test1'}}

Upvotes: 0

Views: 1796

Answers (2)

Doanh Pham
Doanh Pham

Reputation: 11

It's automatically sorted by the browser, so to keep order you got 2 solutions:

  1. You can encode array data first, then encode result array later
$data = [
    '10' => "Test1",
    '3'  => 'Test2',
    '1'  => 'Test3'
];

$result = [
    'code' => '1',
    'data' => json_encode($data)
];
  1. You need change index of array data, you can add _ before each key or anything else to change it to string.
$result = [
    'code' => '1',
    'data' => [
        '_10' => "Test1",
        '_3'  => 'Test2',
        '_1'  => 'Test3'
    ]
];

and then you will get

{
    "code": "1",
    "data": 
    {
        "_10": "Test1",
        "_3" : "Test2",
        "_1" : "Test3"
    }
}

Solution 2 I got from https://stackoverflow.com/a/15806551/5493005

Upvotes: 1

Tanuel Mategi
Tanuel Mategi

Reputation: 1283

So as i understand it, you want to sort your $arr['data'] by key?

this can be done via ksort

$arr = Array('code' => '1', 'data' => Array('10' => "Test1", '3' => 'Test2', '1' => 'Test3'));
//ksort will sort the array depending on the key
ksort($arr['data']);
print_r($arr);
echo json_encode($arr);

result would be

Array
(
    [code] => 1
    [data] => Array
        (
            [1] => Test3
            [3] => Test2
            [10] => Test1
        )

)
{"code":"1","data":{"1":"Test3","3":"Test2","10":"Test1"}}

Live example here

Upvotes: 1

Related Questions