【问题标题】:Does php conserve order in associative array? [duplicate]php是否保存关联数组中的顺序? [复制]
【发布时间】:2012-07-14 07:13:35
【问题描述】:

可能重复:
Are PHP Associative Arrays ordered?

如果我将项目添加到具有不同键的关联数组中,是否保留了添加顺序?如何访问给定元素的“上一个”和“下一个”元素?

【问题讨论】:

    标签: php arrays associative-array


    【解决方案1】:

    是的,php 数组有一个隐含的顺序。使用 resetnextprevcurrent - 或仅使用 foreach loop - 来检查它。

    【讨论】:

      【解决方案2】:

      是的,它确实保留了顺序。您可以将 php 数组视为ordered hash maps

      您可以将元素视为按“索引创建时间”排序。例如

      $a = array();
      $a['x'] = 1;
      $a['y'] = 1;
      var_dump($a); // x, y
      
      $a = array();
      $a['x'] = 1;
      $a['y'] = 1;
      $a['x'] = 2;
      var_dump($a); // still x, y even though we changed the value associated with the x index.
      
      $a = array();
      $a['x'] = 1;
      $a['y'] = 1;
      unset($a['x']);
      $a['x'] = 1;
      var_dump($a); // y, x now! we deleted the 'x' index, so its position was discarded, and then recreated
      

      总而言之,如果您要添加一个条目,其中一个键当前不存在于数组中,则该条目的位置将是列表的末尾。如果您要更新现有键的条目,则位置不会改变。

      foreach 使用上面演示的自然顺序循环数组。如果你愿意,你也可以使用next() current() prev() reset() 和朋友,尽管自从 foreach 被引入语言以来,它们很少使用。

      另外,print_r() 和 var_dump() 也使用自然数组顺序输出它们的结果。

      如果你熟悉java,LinkedHashMap是最相似的数据结构。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-23
        • 1970-01-01
        • 2011-06-21
        相关资源
        最近更新 更多