排序数组不适用于负值(PHP 5.4.16)

时间:2018-06-18 21:08:07

标签: php arrays sorting

为什么这种排序对我的'更改'值不起作用?我尝试了很多不同的方法,但仍然无法使其排序(也有负值)。该脚本在PHP PHP 5.4.16上运行。

$url = 'https://bittrex.com/api/v2.0/pub/Markets/GetMarketSummaries';
$json= file_get_contents($url);
$data = json_decode($json, true);

$items = array();
foreach($data['result'] as $row) {

$base = $row['Market']['BaseCurrency'];

if($base == 'BTC'){

$created = $row['Market']['Created'];
$newDate = date("d-m-Y", strtotime($created));
$last = number_format((float)$row['Summary']['Last'], 8, '.', '');
$prev = number_format((float)$row['Summary']['PrevDay'], 8, '.', '');
$vol = number_format((float)$row['Summary']['BaseVolume'], 2, '.', '');
$name = $row['Market']['MarketCurrencyLong'];
$market = $row['Market']['MarketCurrency'];
$image = $row['Market']['LogoUrl'];

$newName = "$name ($market)";

$change = number_format((float)(1 - $prev / $last) * 100, 2, '.', '');

$items[] = array('name' => $newName, 'change' => $change, 'logo' => $image, 'symb' => $market, 'vol' => $vol, 'date' => $newDate);

}

}

usort($items, function($a, $b) {
            return ($b['change']) - ($a['change']);
            });

echo '<pre>'; print_r($items); echo '</pre>';

1 个答案:

答案 0 :(得分:1)

将比较功能更改为:

return (float)$b['change'] > (float)$a['change'] ? 1 : ((float)$b['change'] < (float)$a['change'] ? -1 : 0);

如果您使用的是PHP 7或更新版本,则可以使用太空飞船运营商

return (float)$b['change'] <=> (float)$a['change'];