json_encode not preserving order

后端 未结 3 2207
醉话见心
醉话见心 2020-12-01 10:45

I have a multi dimensional array, in PHP:

Array
(
[1] => Array
    (
        [19] => Array
            (                    
                [type] =&g         


        
3条回答
  •  抹茶落季
    2020-12-01 11:18

    The problem is that in JavaScript only arrays are ordered, objects are not.

    If you had something like:

    array(
        array(
            'type' => 2
            'id' => 6
        ),
        array(
            'type' => 4
            'id' => 12
        ),
        array(
            'type' => 3
            'id' => 19
        )
    )
    

    Then in your JavaScript you'd have an array of objects, and that array would retain its order.

    The reason it's out of order is because your array's index didn't start at 0, the keys were not in order and there were gaps in the keys. So, when encoded, PHP turned it into an object instead of an array.

提交回复
热议问题