如何在php中从高数字到低数字进行列表


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

假设我有一个这样的变量:

$votes

该变量将存储正数和负数:-1、0、2、3等。)

如何编码一个函数来排列这些数字,但从高到低?

如果是字符串,请使用爆炸,然后排序。如果已经是数组,请使用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 );

编辑;将排序更改为rsort,因为它是从最高到最低,而不是从最低到最高。

这很简单:

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

请参阅:http://php.net/rsort

echo implode(', ', rsort($array));//如果是数组

echo implode(', ', rsort(explode(',', $array)));//如果是字符串

如果$votes是一个数组,只需执行:

rsort($votes, SORT_NUMERIC);

如果是逗号分隔的字符串,则首先使用explode it

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