【问题标题】:What is the fastest way to search for two things in an array of arrays?在数组数组中搜索两个东西的最快方法是什么?
【发布时间】:2014-05-18 06:33:24
【问题描述】:

如果我有两个数字: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 语句来测试一个数组中的数字对是否与在 for 循环中测试的当前元素处的 state_idproduct_id 匹配。显然,如果它们匹配,我希望发生一些事情,(更新价格)。这是最好的方法吗?每个数字对总会有一个匹配项。

这是我目前的设置:

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 用于字典数组中的两个数字?

【问题讨论】:

    标签: php arrays optimization multidimensional-array


    【解决方案1】:

    您的算法是O(n<sup>2</sup>),它非常慢并且根本无法扩展。

    相反,请考虑预先填充查找:

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

    快得多^_^

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多