doutangu4671 2018-06-18 21:08
浏览 30
已采纳

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

Why is this sorting not working for my 'change' value? I tried many different ways but still cannot make it work to sort it (also with negative values). The script is running on 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条回答 默认 最新

  • douhe2305 2018-06-18 21:19
    关注

    Change your comparison function to:

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

    If you had PHP 7 or newer, you could've used spaceship operator:

    return (float)$b['change'] <=> (float)$a['change'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度