Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving order of an associative PHP array while passing it to javascript through ajax

So Here is my php file code

GetUserArray.php

$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);

and this is my ajax request

 $.ajax({
             url: './GetUserArray.php',
             type: 'POST',
             dataType: "json",
             success: function(users) {
                 console.log(users);
                 $.each( users, function( key, value ) {
                 console.log(key, value);
               });
             }

         });

now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file

Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
like image 968
Irtza Shahan Avatar asked Aug 25 '16 01:08

Irtza Shahan


People also ask

Which function is used to sort an associative array?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

Which of the following is used to sort the values of an array object by preserving key values?

The ksort() function sorts the elements of an associative array in ascending order by their keys. It preserves the association between keys and its values while sorting, same as asort() function.

What does array_ filter do in PHP?

The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

What is associative arrays in PHP give some example?

Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.


1 Answers

The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.

So in PHP this works as expected and preserves order.

$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];

foreach($arr as $value) {
    echo $value, "\n";
}

Which gives us

I'm first
I'm second
I'm third

But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.

echo json_encode($arr);

Gives us...

{"4":"I'm first","1":"I'm second","3":"I'm third"}

If you tried to do the same in Javascript with this object you might not get the same order

var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};

var s = "";
for(var x in obj) {
    s += + obj[x] + "\n";
}

document.write("<pre>" + s + "</pre>");

This might give you something more like...

I'm second
I'm third
I'm first

So the only way to fix that is to use an array...

json_encode(array_values($arr));

Now this gives us...

["I'm first","I'm second","I'm third"]

And the order is maintained.

However, if you want to preserve the keys as well, you'll have to create an array of objects.

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

echo json_encode($json);

Now you get...

[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]

Which in javascript, works perfectly as expected...

for(var x in obj) {
    for(var n in obj[x]) {
        obj[x][n]; // now you can both maintain order and have access to the key
    }
}
like image 125
Sherif Avatar answered Nov 14 '22 22:11

Sherif