【问题标题】:$.each doesn't respect the order of an array$.each 不尊重数组的顺序
【发布时间】:2019-01-23 14:46:55
【问题描述】:

我正在尝试在 PHP 中订购一个多维数组,然后将其传递给我的 javascript 文件以显示它。我使用函数$.map$.each 来显示数据。问题是JS根据id对数组重新排序。例如,如果我有这样的数组。

$array = array(1 => array('name' => 'A','last' => 'B'), 
               5 => array('name' => 'C','last' => 'D'),
               2 => array('name' => 'K','last' => 'Z'));

Javascript 会这样排序

    array = {1:{name:'A',last:'B'},2:{name:'C',last:'D'},5:{name:'K',last:'Z'}}

我正在使用 uasort 根据名称对数组进行排序:

public function specialNameComparison($firstElmnt,$secondElmnt){
    if ($firstElmnt['name'] == $secondElmnt['name']) {
        return 0;
    }
    return ($firstElmnt['name'] < $secondElmnt['name']) ? -1 : 1;
}

uasort($users,array($this,'specialNameComparison'));
echo json_encode($users);
die();

正如我所说,在 javascript 中,我正在使用 $.each(我尝试过 $.map)来简单地显示数据

$.each(json, function(key,value) {
   console.log(value.name);
 });

为什么 Javascript 会这样做!?

【问题讨论】:

  • 您没有数组。如果它有 { 和 } 则为对象
  • 扩展 epscarello 所说的,你所拥有的是一个 object,而不是一个 array。不能保证对象上键的顺序。
  • PHP 关联数组成为 javascript 中的对象。 Javascript 本身没有关联数组的概念。
  • 把它转换成一个真正的数组,这样就可以保证顺序了。

标签: javascript php jquery arrays


【解决方案1】:

正如上面评论者指出的那样,您正在创建一个对象而不是 JS 中的数组,没有关联数组,并且表示您的索引会将您置于“类似对象的数组”的上下文中。如果您需要这些钥匙,我会建议您:

$array = [
  [ 'key' => 1, 'name' => 'A','last' => 'B' ], 
  [ 'key' => 5, 'name' => 'C','last' => 'D' ],
  [ 'key' => 2, 'name' => 'K','last' => 'Z' ],
];

json编码时会输出哪个:

[
  { "key": 1, "name": "A","last": "B" }, 
  { "key": 5, "name": "C","last": "D" },
  { "key": 2, "name": "K","last": "Z" },
]

那么你的js可以是:

const arr =  [
  { key: 1, name: 'A',last: 'B' }, 
  { key: 5, name: 'C',last: 'D' },
  { key: 2, name: 'K',last: 'Z' },
];

arr.forEach(({key, name, last }) => console.log(`key: ${key} - ${name} ${last}`))

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多