开发者

How to list from higher numbers to lowers ones in php?

Say I have a variable like this:

$votes

That variable will store positive and negative 开发者_如何学运维numbers: -1, 0, 2, 3, etc...)

How to code a function that arrange those numbers but higher ones to lower ones?


If it's a string, use explode, then sort. If it's already an array, just use sort:

$votes = '-1, 0, 2, 3';
$votes = array_map( 'trim', explode( ',', $votes ) );
rsort( $votes, SORT_NUMERIC );
var_dump( $votes );

// or, if it's already an array:
$votes = array( -1, 0, 2, 3 );
rsort( $votes, SORT_NUMERIC );
var_dump( $votes );

EDIT; Changed sort to rsort, as it's highest to lowest, not vice versa.


This is quite simple:

$votes = array(-1, 0, 2, 3);
$votes = rsort($votes);

print_r($votes);

see: http://php.net/rsort


echo implode(', ', rsort($array)); // if its an array

or

echo implode(', ', rsort(explode(',', $array))); // if its a string


If $votes is an array, just do:

rsort($votes, SORT_NUMERIC);

If it's a comma-delimited string, first explode it

$arr = explode("," $votes);
rsort($arr, SORT_NUMERIC);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜