0

Below is my PHP file.

$test = array('4'=>'test','5'=>'test','1'=>'test','2'=>'test');        
return array(
  "status" => "test
  "data" => $test
);

I am sending this array to AJAX:

$.ajax({
  url: url,
  type: "POST",
  data: {},
  success: function(result) {
    if (result.status == 'test') {
      console.log(result.data);
    }
  }
});

I am getting this output:

{1: "test", 2: "test", 4: "test", 5: "test"}

It is not getting data in the same order as I am sending from PHP. I want to get it in same order as I am sending in PHP. Any help is appreciated. Thanks in advance.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    _I am getting as: {1: "test", 2: "test", 4: "test", 5: "test"}_ That's not possible if you're getting this inside your console.log! Because your condition will never be satisfied – Dhaval Marthak Aug 14 '18 at 09:14
  • 1
    Your data structure is an object, which cannot be sorted. If you want to maintain the ordering, change the logic to use an array instead. – Rory McCrossan Aug 14 '18 at 09:15

2 Answers2

0

The keys in the array are indicating ordering.

If you want a specific order then you should order it as such before sending it to the front end.

I do not believe you can send the data to the front end without it being sorted as its put into the object.

To further aid your testing you might also consider specifying different values in the array.

This way you will be able to differentiate between the different values stored in the array.

0

As mentioned in the comments, if the order of items matters, you need to use arrays, as objects' property order is not guaranteed in JS.

On PHP side, transform your associative array into an array:

$test = array('4'=>'test','5'=>'test','1'=>'test','2'=>'test');
$testArray = array_map(function($key) use($test) { return [$key, $test[$key]]; }, array_keys($test));

return array(
  "status" => "test
  "data" => $testArray
);

On JS side, convert it back into an object:

$.ajax({
  url: url,
  type: "POST",
  data: {},
  success: function(result) {
    if (result.status == 'test') {
      const data = result.data.reduce((result, entry) => ({...result, ...{[entry[0]]: entry[1]}}), {});
      console.log(data);
    }
  }
});

Note: this uses ECMAScript 2018 syntax. There are other ways to merge objects if this is a problem.

Jeto
  • 14,596
  • 2
  • 32
  • 46