php to set order of preference of an Array Sequence using string length -


$records = array(  '123pp' => 3.63,  '123ddd' => 9.63,  '123d' => 6.63,  '123pppp' => 9.63,  '123dd' => 9.63,  '123p' => 2.63,  '123ppp' => 1.53 );  

after looping through records, have 1 value key should 123d because order of preference is: 123d, 123p, 123dd, 123pp, 123ddd, 123ppp, 123pppp...

for e.g.:

  • if 123d not found in array, 123p answer.
  • if 123p not found in array, 123dd answer.

and have found solution :

foreach ($records $key => $value) { if (empty($this->minlength)) { $this->invoicetax = $value;           $this->minlength = strlen($key);         }         elseif (strpos($key, 'p') !== false && (strlen($key) < $this->minlength)) {           $this->invoicetax = $value;           $this->minlength = strlen($key);         }         elseif (strpos($key, 'd') !== false && (strlen($key) <= $this->minlength)) {           $this->invoicetax = $value;           $this->minlength = strlen($key);         } 

but want know if code can optimised not storing string length of every key.

this function tidied solved recursion. means if 123d in array code highly optimised , run once, twice 123p, 3 times 123dd, etc.

function getmostpref($records, $key = "123", $next = "d", $depth = 0) {    if($depth == count($records))    {        // hit end of array nothing found        return false;    }     if(strpos($next, 'd') !== false)    {      // looking @ 'd...' key.      // next key same length key ps.      $nextkey = str_repeat('p', strlen($next));    }    else if(strpos($next, 'p') !== false)    {      // looking @ 'p...' key.      // next key has 1 char , ds.      $nextkey = str_repeat('d', strlen($next)+1);    }    else    {        // key not valid        return false;    }     if(array_key_exists($key.$next, $records))    {       // found key in array return it.       return $records[$key.$next];    }    else    {       // recursive call next key , increased depth.       return getmostpref($records, $key, $nextkey, $depth + 1);    } }   // testing $records = array(  '123pp' => 3.63,  '123ddd' => 9.63,  '123d' => 6.63,  '123pppp' => 9.63,  '123dd' => 9.63,  '123p' => 2.63,  '123ppp' => 1.53 );  // finds 123d , returns 6.63 echo getmostpref($records); 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -