PHP - 从数组中查找上面的确切值或值

时间:2012-06-26 11:08:18

标签: php arrays max

我有一个有效数字的嵌套数组=>数据: -

$validData = array(array(1 => 'one data'),array(5 => '5 data'),array(15 => '15 data'),array(30 => 'thirty data'));

假设我有一个查询值,$ query = 14;

我想首先检查一下是否有14,如果不是,则转到最近的选项ABOVE。

我一直在用max,array_keys和范围做最近的项目。但是,出于某种原因匹配或上述我看不到最佳方式?

2 个答案:

答案 0 :(得分:1)

假设数组已排序

$query = 14;
$arrayThatWeWant = null;
foreach ( $validData as $index=>$vdSubRay)
{
    $ak = key($vsSubRay);
    if ( $ak == $query )
    {
        $arrayThatWeWant = $vdSubRay;
        break;
    }
    else if ( $ak > $query )
    {
        $arrayThatWeWant = $validData[$index-1];
        break;
    }
}

答案 1 :(得分:1)

// in case your array keys are already sorted
$prevKey = key(current($validData));
foreach($validData as $data) {
    $currentKey = key($data);
    if ($currentKey == $query) {
        // found !
        echo $currentKey;
        break;
    }
    else if ($currentKey > $query) {
        echo $currentKey;    
        break;
    }
    $prevKey = $currentKey;
}