Skip to content
Advertisement

How to get array id and name values display in the same order on javascript after ajax call?

I have an array in php which look like below:

    if(count($rows)) {
    $new = array();
    foreach($rows as $row) {
        $new[$row['id']] = $row['sel_date']." - ".date('l',$row['date_timestamp']);     
        //$myobj->id = $row['id'];
    }
}

Now on php page I have two option to pass my array back to the javascript ajax funtion: either

print_r($new) or echo json_encode($new)

However, when I send using json_encode($new) from php page to javascript page it lost the order of the php array keys. so for example my php new array look like below:

Array
(
[71] => 07/09/2019 - Saturday
[81] => 08/09/2019 - Sunday
[83] => 09/09/2019 - Monday
[84] => 10/09/2019 - Tuesday
[72] => 15/09/2019 - Sunday
[73] => 16/09/2019 - Monday
[74] => 17/09/2019 - Tuesday
[75] => 18/09/2019 - Wednesday
)

Now on javscript side if I use JSON.parse(data) then the order will be like the below

Array
(
[71] => 07/09/2019 - Saturday
[72] => 15/09/2019 - Sunday
[73] => 16/09/2019 - Monday
[74] => 17/09/2019 - Tuesday
[75] => 18/09/2019 - Wednesday
[81] => 08/09/2019 - Sunday
[83] => 09/09/2019 - Monday
[84] => 10/09/2019 - Tuesday

)

Which I don’t want happen as the json.parse rearranging the order of php array.

So what should I do to maintain the order and how I can loop through php returned array on javascript side so that my order remain same?

Thanks & was spending a lot of time to get this done but json.parse() is not allow me to maintain the order of php array and don’t know any other way to loop through php array on javascript side.

Many people didnt get the answer right as I checked many other posts on stackoverflow but didn’t get my answer thr. So please don’t refer any other posts here.

Advertisement

Answer

JSON_ENCODE in PHP preserves the key order but the same is not true in Javascript.

In PHP:

$arr = [3 => "A", 1 => "B", 2 => "C"];
echo json_encode($arr);

Output:
{"3":"A","1":"B","2":"C"}

But if you try same in Javascript

var obj = {"3":"A","1":"B","2":"C"};
console.log(JSON.stringify(obj));

Output:
"{"1":"B","2":"C","3":"A"}"

To preserve the key order in javascript too, you need to make the array of object in PHP.

$newArr = [];
foreach($arr as $key => $value){
    $newArr[] = [$key => $value];
}

echo json_encode($newArr);

Output:
[{"3":"A"},{"1":"B"},{"2":"C"}]

Now you can access same in Javascript.

arrObj = JSON.parse(str);

arrObj.forEach(function(element) {
    for (strKey in element) {
        console.log(strKey + ' : ' + element[strKey]);
    }
});

Output:
3 : A
1 : B
2 : C
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement