2014-04-05 53 views
0

如果我有兩個數字:state_idproduct_id找出一對是否作爲我的數組中的元素存在的最佳方法是什麼? 這裏是我的數組是什麼樣子:在數組數組中搜索兩件事物的最快方法是什麼?

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 
     ) 
) 

我想通過每個元素迭代並具有if語句來測試是否被測試從當前元素一個陣列同時匹配state_idproduct_id數對反對for循環。顯然,如果他們匹配,我想要發生一些事情(更新價格)。這是最好的辦法嗎?每個號碼總會有一個匹配。

這是我的當前設置:

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 
     } 
    } 
} 

這是去它的最好的辦法,還是有一個更快的方式search兩個數與字典中的數組?

回答

4

你的算法是O(n2),這是非常緩慢的,並不是所有可擴展的。

相反,考慮預填充查找:

$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! 
    } 
} 

快得多^ _^

相關問題