开发者

php assoc array find that item just before that value

I have an associative array, say:

$a=array('x'=>3,'y'=>6,'z'=>12);

and a value, say $c=9

From this, how can I get the last element before the value $c in $a?

EG: if $c=4, then return 'x', if its 99 return 'z', if its 7 return 'y' if its 11 return 'y'..开发者_如何转开发.that sort of thing...


<?php
function func($c)
{
  $a = array('x'=>3,'y'=>6,'z'=>12);

  $previous = null;

  foreach($a as $k => $v)
  {
     if($v > $c) // This part was unclear, so it could be >= instead
     {
        return $previous;
     }
     $previous = $k;
  }
  return $previous;
}

func(9);


Try this:

function getKey($array, $value)
{
    $result = null;
    foreach ($array as $key => $item)
    {
        if ($item > $value)
        {
            break;
        }
        else
        {
            $result = $key;
        }
    }

    return $result;
}

$a = array('x'=>3,'y'=>6,'z'=>12);
$c = 9;
getKey($a, $c);


function getValueBefore($needle, $a){
foreach ($a as $key => $val) {
//Get the distance of each key's value from the search val    
$offset[$key] = $val-$haystack;
//if the offset is positive, unset it, we have gone past
    if($offset[$key]>0){unset($offset[$key]);}
}
//Sort the array by distance from the search value so the highest negative offset is shifted off
arsort($offset);
//flip the array so the key is returned instead of the offset distance
$offset = array_flip($offset);
return array_shift($offset);
}

Called like

$haystack = array('x' => 3, 'y' => 6, 'z' => 12);
$needle = 7;
getValueBefore($needle, $haystack);
//returns 'y'

This will return the string key (ie x,y,z)


As you build the '$a' array, also build a companion array except where the numbers are the keys and the letters are the values (e.g. $_a=array(3=>'a',6=>'y', 12=>'z');

Then you can do array_keys on this new array e.g. (3, 6, 12), sort them and walk through until you find the one that is bigger than the one you're checking.

For extra credit, rather than search linearly do a newton search - start at size($_a) / 2; if too big, go to size($_a)*3/4, else size($_a)*1/4

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜