0

I'm trying to order a multidimensional array in PHP and then pass it to my javascript file to display it. I use the function $.map and $.each to display the data. The problem is that the JS reorder the array according to the id. eg if I have an array like this.

$array = array(1 => array('name' => 'A','last' => 'B'), 
               5 => array('name' => 'C','last' => 'D'),
               2 => array('name' => 'K','last' => 'Z'));

Javascript will sort it this way

    array = {1:{name:'A',last:'B'},2:{name:'C',last:'D'},5:{name:'K',last:'Z'}}

I'm using uasort to sort my array according to the name :

public function specialNameComparison($firstElmnt,$secondElmnt){
    if ($firstElmnt['name'] == $secondElmnt['name']) {
        return 0;
    }
    return ($firstElmnt['name'] < $secondElmnt['name']) ? -1 : 1;
}

uasort($users,array($this,'specialNameComparison'));
echo json_encode($users);
die();

And in javascript as I said i'am using $.each (I've tried $.map to) to simply display the data

$.each(json, function(key,value) {
   console.log(value.name);
 });

Why Javascript is doing this !?

KubiRoazhon
  • 1,759
  • 3
  • 22
  • 48

1 Answers1

3

As above commenters have pointed out you are creating an object not an array in JS there are no associative arrays and denoting your indices puts you into the context of an 'array like object'. if you need those keys I would advise something like:

$array = [
  [ 'key' => 1, 'name' => 'A','last' => 'B' ], 
  [ 'key' => 5, 'name' => 'C','last' => 'D' ],
  [ 'key' => 2, 'name' => 'K','last' => 'Z' ],
];

which when json encoded will output:

[
  { "key": 1, "name": "A","last": "B" }, 
  { "key": 5, "name": "C","last": "D" },
  { "key": 2, "name": "K","last": "Z" },
]

then your js can be:

const arr =  [
  { key: 1, name: 'A',last: 'B' }, 
  { key: 5, name: 'C',last: 'D' },
  { key: 2, name: 'K',last: 'Z' },
];

arr.forEach(({key, name, last }) => console.log(`key: ${key} - ${name} ${last}`))
D Lowther
  • 1,609
  • 1
  • 9
  • 16