Reputation: 10294
I have return the following json response from my server side -
echo json_encode(array("result"=>"success", "networks" => $adNetworkListFinal));
Where, taking an example, $adNetworkListFinal has the following value -
Array
(
[-3] => Native Test
[143] => conf native template
[142] => test native
)
Note - index -3 is the first one. Yes, it is a negative integer index, which I am having to use here.
But, in the client side, when I traverse the response with a .each(), I get the item with index -3
at last -
Code
$.ajax({
type: "POST",
url: posturl,
data : data,
dataType: "json",
async: false,
success: function(msg){
if (msg.result == "success")
{
$.each(msg.networks,function(key,val)
{
console.log("check "+key);
});
}
});
Output
check 142
check 143
check -3
I am not sure what is causing the change in order (item indexed -3 is getting accessed at last), and how to fix it.
Upvotes: 0
Views: 339
Reputation: 944020
Arrays cannot have negative indexes so you are creating a JSON object (and hence a JavaScript object).
JSON and JavaScript objects are unordered so you get the properties back in whatever order the JS engine cares to store them in.
Since the values are numerical, you can pull them into an array (as values, not indexes) and sort them before using them to access the values of the original object.
Upvotes: 2