Pavan
Pavan

Reputation: 18538

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

If I have two numbers: state_id and product_id what is the best way to find out if a pair exists as an element within my array? Here is what my 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 was thinking of iterating through each element and having an if statement that tests whether the number pairs from one array match both the state_id and product_id at the current element being tested against in the for loop. Obviously I want something to happen if they do match, (update the price). Is this the best way to go about it? There will always be a match for every number pair.

This is my 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 the price for myOwnArray by grabbing the price from the StateProductPricesArray   
        }
    }
}

Is this the best way to go about it, or is there a faster way to search for two numbers in an array with dictionaries?

Upvotes: 0

Views: 62

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

Your algorithm is O(n2), which is very slow and not at all scaleable.

Instead, consider pre-populating a lookup:

$separator = " -- "; // any separator is okay, so long as it doesn't appear in values
$map = array();
foreach($stateProductPriceArray as $i=>$item) {
    $map[$item['State_Id'].$separator.$item['Product_Id']] = $i;
}

foreach($myOwnArray as $row) {
    if( isset($map[$row['State_Id'].$separator.$row['Product_Id']])) {
        $product = $stateProductPriceArray[$map[$row['State_Id'].$separator.$row['Product_Id']]];
        // do something!
    }
}

Much faster ^_^

Upvotes: 4

Related Questions