【问题标题】:How to sort an array with a limit?如何对有限制的数组进行排序?
【发布时间】:2012-11-09 15:20:09
【问题描述】:

我想使用asort() 对数组进行排序并限制要返回的元素数量。

我举个例子:

$words = array (
["lorem"]=>
int(2)
["sssss"]=>
int(2)
["dolor"]=>
int(4)
["ipsum"]=>
int(2)
["title"]=>
int(1) );

with =limit = 2 我希望得到回报:

  $words = array (
    ["dolor"]=>
    int(4)    
    ["lorem"]=>
    int(2));

换句话说,我必须根据$limit 仅对第一次出现的事件进行排序并返回

有什么想法吗?

【问题讨论】:

    标签: php arrays sorting asort


    【解决方案1】:

    你可以使用array_slice

    asort($words);
    $result = array_slice($words, 0, $limit);
    

    【讨论】:

      【解决方案2】:

      您不能对 asort() 应用限制,但这是一种解决方法。

      <?php 
         $words = array("Cat", "Dog", "Donkey");
         $sorted = asort($words);
         $limit = 2;
         $final = array();
         for ($i = 0; $i <= ($limit - 1); $i++) {
             $final[] = $words[$i];
         }
         var_dump($final);
      ?>
      

      希望这会有所帮助。

      【讨论】:

      • 第二个没有意义。他想要排序顺序最高的两个元素,而不是排序顺序中的前两个。
      • 是的,谢谢,删除了不需要的解决方案。无论哪种方式,array_slice 都是更好的解决方案。干杯。
      • 您的解决方案完全有效且易于理解。
      • 注意asort返回一个布尔值,asort是为关联数组设计的。
      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2018-04-21
      • 2022-01-20
      • 2021-12-12
      • 1970-01-01
      • 2019-12-11
      相关资源
      最近更新 更多