1

when i return a key pair array in php to ajax call at jquery (javascript) end the order i have maintain in php get lost. how to preserve array order.

e.g array('node' => 'abc', 'test' => 'xyz', 'a' => 'xyz') this array disorder to array('a' => 'xyz', 'node' => 'abc', 'test' => 'xyz') in jquery. Any help.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

1 Answers1

0

JavaScript has no concept of an associative array as in PHP, so when you JSON encode something, it becomes an object instead. The ordering of object keys isn't important, so relying on them could lead to unexpected behaviour.

If ordering is important, you should consider using a non-associative array with objects (or associative arrays) as values.

$myArray = array(
    array('x' => 'node', 'y' => 'abc'),
    array('x' => 'test', 'y' => 'xyz'),
    array('x' => 'a',    'y' => 'xyz'),
);

That would encode as:

[
    {"x": "node", "y": "abc"},
    {"x": "test", "y": "xyz"},
    {"x": "a",    "y": "xyz"}
]
Kevin Nagurski
  • 1,889
  • 11
  • 24