dtbonklcs575884485 2015-01-17 07:33
浏览 61
已采纳

返回数组中大于X的数字

The following code automagically finds the highest price on a page:

    $vw_link = get_field('shop_link');

    $ch = curl_init($vw_link);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $cl = curl_exec($ch);

    $dom = new DOMDocument();
    @$dom->loadHTML($cl);
    $xpath = new DOMXpath($dom);

    $price = $xpath->query("//span[@class='price']");

    foreach($price as $value) { 
    $vw_array[] =  floatval(str_replace('$', '', $value->nodeValue));
    update_field('shop_price',max($vw_array));
    }

What would be the best thing since sliced cheese is if it could return the value in $vw_array that is between a specific amount, ie, greater than 100 and less than 200. The tricky part would be returning the first greatest number after 100, if there are multiple numbers between 100-200.

For example (if the following prices are all wrapped in 'price' class):

$88

$92

$105  <-- return this number

$125

$180

$210

Does anyone know how to conjure up such a magnificent function?

  • 写回答

4条回答 默认 最新

  • douzhanlie9209 2015-01-17 07:54
    关注
    function getHighestValue($arr, $high = 200, $low =100) {
        $data = $arr;
        // sort it so you can find 1st highest value in range
        asort($data);
    
        foreach ($data as $item) {
        //trim dollar sign as i can see from your example
            $item = ltrim($item, "$");
            if ($item >= $low && $item <= $high) {
                return $item;
            }
        }
      return false;
    }
    

    So if your data is

    $arr = [
        '$140',
        '$22',
        '$143',
        '$199',
    ];
    
    var_dump(getHighestValue($arr)); // will return 140
    

    Also you can add dollar sign back after that

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?