douluchuo0801 2012-09-04 16:55
浏览 37
已采纳

没有获得金钱字符串数组的最大和最小值

This is my array

Array ( [0] => $30.00 [1] => $200.00 [2] => $138.00 [3] => $100.00 [4] => $30.00 
[5]=>$30.00 [6] => $30.00 )

Trying to get the max and min value from this array

echo $maxprice = max($list);
echo $minprice = min($list);

I get $30.00 for max and $100.00 for min

I am guessing this is due to the values are in money string.

Can someone please tell me how I could get the real max and min for this array? Is this really due to money string?

Thanks in advance

Note This array is stripped down from a multidimensional array. If it was normal array, it would be straightforward

  • 写回答

3条回答 默认 最新

  • duangan9251 2012-09-04 16:58
    关注

    You need to use decimal values (without the "$") in your array. The dollar sign should only be applied when outputting to display.

    To get the string converted to floats, you can just array_walk() the array.

    If on PHP 5.3 or greater, I like to use closures like this

    array_walk($array, function (&$value, $key) {
       $value = (float)ltrim($value, '$');
    });
    

    If in older version of PHP, you would need to define a separate function and call the function in array_walk like this

    array_walk($array, 'strip_dollar_signs');
    
    function strip_dollar_signs (&$value, $key) {
        $value = (float)ltrim($value, '$');
    }
    

    Then just sort your array as you typically would

    sort($array, SORT_NUMERIC);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源