0

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

$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 和 range 做最近的项目。但是,出于某种原因,匹配或超越我看不到最好的方法?

4

2 回答 2

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;
    }
}
于 2012-06-26T11:18:42.740 回答
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;
}
于 2012-06-26T11:21:24.070 回答