javascript - 通过ajax将关联PHP数组传递给javascript时保留其顺序

标签 javascript php jquery arrays ajax

这是我的 php 文件代码

获取用户数组.php

$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);

这是我的 ajax 请求

 $.ajax({
             url: './GetUserArray.php',
             type: 'POST',
             dataType: "json",
             success: function(users) {
                 console.log(users);
                 $.each( users, function( key, value ) {
                 console.log(key, value);
               });
             }

         });

现在它在控制台中给我的是一个按该数组的键排序的对象,而我想要我的 php 文件中的原始顺序为 7 4 10

Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia

最佳答案

使用 HashMap 的问题是它们实际上并不指定顺序。不过,在 PHP 中,数组实际上是一个有序的 HashMap ,所以确实如此。一旦将其转换为 Javascript 中的对象,顺序就不再保留。在 Javascript 中保证顺序的唯一方法是使用数组。

因此,在 PHP 中,这会按预期工作并保留顺序。

$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];

foreach($arr as $value) {
    echo $value, "\n";
}

这给了我们

I'm first
I'm second
I'm third

But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.

echo json_encode($arr);

给我们...

{"4":"I'm first","1":"I'm second","3":"I'm third"}

If you tried to do the same in Javascript with this object you might not get the same order

var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};

var s = "";
for(var x in obj) {
    s += + obj[x] + "\n";
}

document.write("<pre>" + s + "</pre>");

这可能会给你一些更像......

I'm second
I'm third
I'm first

So the only way to fix that is to use an array...

json_encode(array_values($arr));

现在这给了我们...

["I'm first","I'm second","I'm third"]

And the order is maintained.

However, if you want to preserve the keys as well, you'll have to create an array of objects.

$json = [];
foreach($arr as $key => $value) {
    $json[] = [$key => $value];
}

echo json_encode($json);

现在你得到...

[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]

Which in javascript, works perfectly as expected...

for(var x in obj) {
    for(var n in obj[x]) {
        obj[x][n]; // now you can both maintain order and have access to the key
    }
}

关于javascript - 通过ajax将关联PHP数组传递给javascript时保留其顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39135555/

相关文章:

jquery - 使用 JQuery 在导航栏中切换事件类

javascript - 我无法让我的文本输入将 <li> 附加到我的 html 中的空白 <ul>

javascript - cytoscape.js webgl 渲染器

javascript - 为什么 AJAX 成功调用中的代码不起作用?

javascript - Jquery datepicker,如何设置 future 日期

php - 使用 PHP 通过 id 从数据库中删除特定条目

javascript - 如何阻止jsp执行

javascript - php变量与javascript的连接

php - 计算 Ubuntu 中的逻辑代码行

javascript - 在创建事件中动态设置 jQuery ui slider 值