【问题标题】:Searching a array in PHP, performance improvements在 PHP 中搜索数组,性能改进
【发布时间】:2013-07-05 13:21:34
【问题描述】:

我有两个 A 和 B 数组,第一个 (A) 是简单数组,而第二个 (B) 是数组数组。我想找出 A 中的某个元素是否等于 B 中的元素。为此,我目前正在执行嵌套循环,这会导致 n^3 复杂性。我该如何改进。

for ($i = 0; $i <= count($A); $i++) {
    if (isset($A[$i])) {
        foreach ($B as $items) {
            foreach ($items as $item) {
                if ($item['Column1'] == $A[$i]['Column1']) {
                    array_push(A, "result");
                    unset($A[$i]);
                    unset($items);
                    break;
                }
            }
        }
    }
}

【问题讨论】:

  • 请提供数组示例和想要的结果。

标签: php algorithm search complexity-theory


【解决方案1】:

在创建数组时,您可以创建 $lookup_A 和 $lookup_B 数组,其中键是原始 $A 和 $B 中的值

然后你可以在 $lookup_A 上做一个简单的循环并检查 if (isset($lookup_B[$lookup_A_key]))

在你的例子中,我认为 if(isset($A[$i])) 总是正确的

【讨论】:

    【解决方案2】:
    array_walk_recursive($B, function($val) {
      if (in_array($val, $A)) echo "$val is in the \$A array!";
    });
    

    【讨论】:

    • 一个简单的in_array不能工作,$B数组是多维的
    【解决方案3】:

    试试这个,array_seacrh() 将删除你的一个 foreach 循环:

    for ($i = 0; $i <= count($A); $i++) {
        if (isset($A[$i])) {
            foreach ($B as $items) {
                $t = array_search($A[$i]['Column1'], $items);
                array_push($A, "result");
                unset($A[$i]);
                unset($items[$t]);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2011-10-11
      • 2016-01-15
      相关资源
      最近更新 更多