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 !?