返回数组中大于X的数字 [英] Return number in array that is greater than X

查看:87
本文介绍了返回数组中大于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));
    }

最好的事情是切成薄片的奶酪,如果它可以返回$ vw_array中特定值(即大于100小于200)之间的值,那么棘手的部分将是首先返回 如果在100-200之间有多个数字,则为100之后的最大数字.

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.

例如(如果以下价格都包含在"price"类中):

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?

推荐答案

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;
}

因此,如果您的数据是

$arr = [
    '$140',
    '$22',
    '$143',
    '$199',
];

var_dump(getHighestValue($arr)); // will return 140

还可以在此之后添加美元符号

Also you can add dollar sign back after that

这篇关于返回数组中大于X的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆