[英]How to get elements of an associative array in the same order as it was entered
我在javascript(关联数组)中有一个带有数字键和值的对象,我将ajax传递给PHP,然后通过它。 我的问题是,在PHP中运行数组是通过对键进行数字挤奶而不是按输入数据的相同顺序来运行的。
Java脚本
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 " / ";
}
这是在javascriot中的对象中输入的数据的示例,以及在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
简单,
不要使用数字键作为数组索引,而要使用递增索引,然后使用另一个数组作为值。 像这样:
var ix = 1;
$("#example li").each(function(){
key = $(this).attr("id"); //A number
value = $(this).attr("value"); //Another number
object[ix++] = [key, value];
}
然后在PHP中检索对象:
foreach ($object as $row ) {
echo $row[0];
echo "-";
echo $row[1];
echo " / ";
}
如果这仍然与众不同,那么您可以继续使用旧方法:)
for ($i = 1; $i< count($object); $i++ ) {
echo $object[$i][[0];
echo "-";
echo $object[$i][1];
echo " / ";
}
我将数据追加到数组中,将数据发布如下:
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} );
在PHP方面:
foreach($_POST['assoc'] as $arr){
echo $arr['id'] . '->' . $arr['value'];
}
foreach($_POST['numeric'] as $arr){
echo $arr[0] . '->' . $arr[1];
}
另外,您可以将订单作为数组传递并循环执行以下操作:
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
使用order数组的值访问对象:
$object = $_POST['object'];
foreach($_POST['order'] as $key) {
echo $object[$key];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.