The php associated array finds this element immediately before this value.

I have an associative array, say:

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

and value e.g. $c=9

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

EG: if $ c = 4, then return 'x', if its 99 returns 'z', if its 7 returns 'y', if its 11 returns 'y' ... such a thing ...

+4
source share
4 answers
 <?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); 
+2
source

Try the following:

 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); 
+1
source
 function getValueBefore($needle, $a){ foreach ($a as $key => $val) { //Get the distance of each key 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 as

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

This will return a string key (i.e. x, y, z)

+1
source

When you create an array of $ a, also create an array of companions, unless numbers are keys and letters are values ​​(e.g. $ _a = array (3 => 'a', 6 => 'y', 12 = > 'z');

Then you can do array_keys in this new array, for example. (3, 6, 12), sort them and go through until you find one that is larger than the one you are checking.

For an additional loan, rather than a search, linearly search for newton - start with the size ($ _ a) / 2; if it is too large, go to the size ($ _ a) * 3/4, otherwise the size ($ _ a) * 1/4

0
source

Source: https://habr.com/ru/post/1342714/


All Articles