双循环移除项目

时间:2016-06-13 08:32:42

标签: php arrays loops

我想在某些条件下从字典中删除单词。 我想这样做,在下一次迭代中,字典将计算新的字典,删除最后一项,因此它不会再次计算。

// sample data
    $dict = ['aaa', 'aaan','aba', 'abat', 'ime', 'iso', 'nime', 'tiso',];
    $unique = ['abatiso', 'aaanime'];

  // could use while to further optimize unset (and remove on the fly) http://php.net/manual/en/control-structures.foreach.php#88578
    while (list($key_word, $word) = each($unique)) { // $key is unused, just for the optimization that the whille provides
      foreach ($dict as $key_other => $other) {

// ... conditions calculations

        unset($unique[$key_word]);
 }
}
    echo "n compounds: " . count($compounds) . NL;

如果我将内循环设置为while而不是foreach作为外部,我得到0结果,它会立即终止。

目前,我得到的重复结果如下:

               // Removed: abatiso => wc: aba + tiso = abatiso
                // Removed: abatiso => wc: abat + iso = abatiso
                // Removed: abatiso => wc: abati + so = abatiso
                // Removed: abatiso => wc: abatis + o = abatiso

我怎样才能删除这个词并在下一次迭代中再次获取它?

一些测试数据:

Removed: aaaaaah => wc: aaaa + aah = aaaaaah
Removed: aaaaaah => wc: aaaaaa + h = aaaaaah
Removed: aaaaargh => wc: aaa + aargh = aaaaargh
Removed: aaaalead => wc: aaaa + lead = aaaalead
Removed: aaabbbccc => wc: aaab + bbccc = aaabbbccc
Removed: aaacomix => wc: aaa + comix = aaacomix
Removed: aaagak => wc: aaa + gak = aaagak
Removed: aaahh => wc: aaa + hh = aaahh
Removed: aaainc => wc: aaa + inc = aaainc
Removed: aaainc => wc: aaai + nc = aaainc
Removed: aaanet => wc: aaa + net = aaanet
Removed: aaanet => wc: aaan + et = aaanet
Removed: aaanime => wc: aaa + nime = aaanime
Removed: aaanime => wc: aaan + ime = aaanime
Removed: aaaron => wc: aaa + ron = aaaron
Removed: aabbcc => wc: aab + bcc = aabbcc
Removed: aabmup => wc: aab + mup = aabmup
Removed: aabre => wc: aab + re = aabre
Removed: aabybro => wc: aaby + bro = aabybro
Removed: aacap => wc: aac + ap = aacap
Removed: aacap => wc: aaca + p = aacap
Removed: aaccording => wc: aac + cording = aaccording
Removed: aacd => wc: aac + d = aacd
Removed: aachener => wc: aach + ener = aachener
Removed: aachener => wc: aachen + er = aachener
Removed: aacisuan => wc: aaci + suan = aacisuan
Removed: aacisuan => wc: aacis + uan = aacisuan
Removed: aacult => wc: aac + ult = aacult

我没有在内循环中使用中断,因为我还必须进行计算。

1 个答案:

答案 0 :(得分:0)

您的代码中存在错误。您将$key值设置在两个具有两种不同含义的位置。首先,您在list(..语句中分配,然后在foreach循环中再次分配为$dict中值的关键值持有者。

根据经验,在迭代该列表时从列表中取消设置元素永远不会有好处。您最好将处理的项目保存在列表中,不要再处理它们。如果您愿意,可以稍后删除这些项目, 后完成unique的循环。

如果我理解你的问题,这将是一种方法:

$toUnset = [];
foreach ($unique as $key => $word) {
    if (!in_array($word, $toUnset)) {
        foreach ($dict as $other) {

            //do your processing
            $toUnset[] = $word;
        }
    }
}