Joseph
Joseph

Reputation: 859

How to get elements of an associative array in the same order as it was entered

I have an object in javascript (associative array) with numeric key and value and I pass through ajax to PHP and then go through it. The problem I have is that running the array in PHP is run by milking the keys numerically instead of showing in the same order that the data were entered.

Javascript

var object = new Object();

$("#example li").each(function(){
  key = $(this).attr("id"); //A number
  value = $(this).attr("value"); //Another number

  object[key] = value;
});

 // Pass the object by ajax to PHP

  ....

PHP

... // We retrieved the object in php

foreach ($object as $key => $value ) {
  echo $key;
  echo "-";
  echo $value;
  echo " / ";
}

Here is an example of the data entered in the object in javascriot and the order in which it appears after traversing it in php:

 Input data:   43->63 , 29->63, 33->63, 30->63, 44->63  (key->value)

 Output data:   29-63 / 30-63 / 33-63 / 43-63 / 44-63

Upvotes: 0

Views: 368

Answers (3)

Xorifelse
Xorifelse

Reputation: 7911

I would append the data to an array post the data like so:

var a = []; // post assoc
var b = []; // post numeric

$("#example li").each(function(){
  idv  = $(this).attr("id");
  val = $(this).attr("value");

  a.push({id: idv, value: val});
  b.push([idv, val]);
});

$.post('script.php',{assoc: a, numeric: b} );

And on the PHP side:

foreach($_POST['assoc'] as $arr){
  echo $arr['id'] . '->' . $arr['value'];
}

foreach($_POST['numeric'] as $arr){
  echo $arr[0] . '->' . $arr[1];
}

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

As an alternate you can pass the order as an array and loop that:

var object = new Object();
var order  = [];

$("#example li").each(function(){
  key = $(this).attr("id"); //A number
  value = $(this).attr("value"); //Another number

  object[key] = value;
  order.push(key);
});

 // Pass the object by ajax to PHP

Access the object with the value of the order array:

$object = $_POST['object'];

foreach($_POST['order'] as $key) {
  echo $object[$key];
}

Upvotes: 1

Nelson Teixeira
Nelson Teixeira

Reputation: 6570

Easy,

instead of using the numeric key as the array index, use a incremented index, and use another array as value. Like this:

var ix = 1;
$("#example li").each(function(){
  key = $(this).attr("id"); //A number
  value = $(this).attr("value"); //Another number
  object[ix++] = [key, value]; 
}

Then to retrieve the object in PHP:

foreach ($object as $row ) {
  echo $row[0];
  echo "-";
  echo $row[1];
  echo " / ";
}

if this still is out of other you can allways go back to old ways :)

for ($i = 1; $i< count($object); $i++ ) {
  echo $object[$i][[0];
  echo "-";
  echo $object[$i][1];
  echo " / ";
}

Upvotes: 1

Related Questions