如何对数组进行排序?

Alu*_*ard 1 php arrays sorting asort

我想使用数组排序asort()并限制要返回的元素数.

让我举个例子:

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

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

  $words = array (
    ["dolor"]=>
    int(4)    
    ["lorem"]=>
    int(2));
Run Code Online (Sandbox Code Playgroud)

换句话说,我将不得不排序并仅返回基于的第一次出现 $limit

任何的想法 ?

xda*_*azz 8

你可以使用array_slice

asort($words);
$result = array_slice($words, 0, $limit);
Run Code Online (Sandbox Code Playgroud)