php - What is the fastest way to search for two things in an array of arrays? -


if have 2 numbers: state_id , product_id best way find out if pair exists element within array? here array looks like:

array (     [0] => array         (             [stateproduct_id] => 1             [state_id] => 2             [product_id] => 1             [stateproduct_price] => 160         )      .....      [102] => array         (             [stateproduct_id] => 103             [state_id] => 10             [product_id] => 5             [stateproduct_price] => 210         ) ) 

i thinking of iterating through each element , having if statement tests whether number pairs 1 array match both state_id , product_id @ current element being tested against in loop. want happen if match, (update price). best way go it? there match every number pair.

this current setup:

for($i = 0; $i < count($myownarray); $i++){     for($n = 0; $n < count($stateproductpricesarray); $n++){         if(    $stateproductpricesarray[$n]['state_id'] == $myownarray[$i]['state_id']             &&  $stateproductpricesarray[$n]['product_id'] == $myownarray[$i]['product_id']){             //do something. update price myownarray grabbing price stateproductpricesarray            }     } } 

is best way go it, or there faster way search 2 numbers in array dictionaries?

your algorithm o(n2), slow , not @ scaleable.

instead, consider pre-populating lookup:

$separator = " -- "; // separator okay, long doesn't appear in values $map = array(); foreach($stateproductpricearray $i=>$item) {     $map[$item['state_id'].$separator.$item['product_id']] = $i; }  foreach($myownarray $row) {     if( isset($map[$row['state_id'].$separator.$row['product_id']])) {         $product = $stateproductpricearray[$map[$row['state_id'].$separator.$row['product_id']]];         // something!     } } 

much faster ^_^


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -