[英]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.