0

I have a nested array with valid numbers => data:-

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

Let say I have a query value, $query = 14;

I want to first check if there's a 14, if not then go to the nearest option ABOVE.

I've been doing nearest item with max, array_keys and ranges. But, matching or going above for some reason I can't see the best way?

2
  • Sort the array, loop through the array remembering the previous item, if you're past the item, use the previous item... Commented Jun 26, 2012 at 11:10
  • Or, loop through the array in reverse and stop when you find an item with key($item) <= $query. Commented Jun 26, 2012 at 11:15

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

sorry didn't notice the nearest option ABOVE. Just fixed it.
1

Assuming the array is sorted

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.