根据条件从数组中删除值

时间:2018-11-30 14:54:31

标签: php algorithm

这比PHP问题更多是算法问题,但我似乎无法弄清楚!

我有一个多维数组,如下所示:

[
    210875 => ["2", "1"],
    129096 => ["2", "2"]
]

有2个ID,但可能还有更多。根据这些条件,我只想在表中保留1个ID。

伪代码:

if a[0] == 1 and a[1] >= 1: # the id gets deleted right away without looking at other conditions
if a[0] >= 2 and a[1] == 2: # it stays if nothing below fits else it gets deleted
if a[0] >= 3 and a[1] == 3: # it stays if nothing below fits else it gets deleted
if a[0] >= 8 and a[1] == 4: # it stays if nothing below fits else it gets deleted
# ... etc

如果两个条件相同,则其中一个会被随机删除。

例如(伪代码):

a[0] == 2 and a[1] == 1
a[0] == 2 and a[1] == 2

我尝试执行以下操作,但是我不知道如何动态地使if条件取决于我的算法:

$sub_array = array();
foreach($array as $k=>$v) {
    if($v[0] == 1 && $v[1] == 1) continue;
    if($v[0] >= 2 && $v[1] == 2) $sub_array[$k] = $v;
    if($v[0] >= 6 && $v[1] == 3) $sub_array[$k] = $v;
    if($v[0] >= 8 && $v[1] == 4) $sub_array[$k] = $v;
    // etc ...
}

此外,当我这样做时,如何知道子数组中哪个是最高的?

1 个答案:

答案 0 :(得分:0)

我尚不清楚您的条件是什么,但对我来说,您似乎确实在对每一行进行排名,最后您希望将行保持在最高排名。

即使我对您的规则的解释可能与您的意图不完全相同,您也可以通过调整以下代码中的分数来对其进行调整。我还建议交换条件,以便首先进行==比较。这样会更有效率:

$keepKey = null;
$bestScore = -1;
foreach($array as $k=>$v) {
    $score = 0;
    if ($v[1] == 1 && $v[0] == 1) $score = 1;
    if ($v[1] == 2 && $v[0] >= 2) $score = 2;
    if ($v[1] == 3 && $v[0] >= 6) $score = 3;
    if ($v[1] == 4 && $v[0] >= 8) $score = 4;
    // ... etc ...
    if ($score > $bestScore) {
        $keepKey = $k;
        $bestScore = $score;
    }
}

$sub_array = [$keepKey => $array[$keepKey]]; // Only keep the entry with highest score

如果重要的是在平局中随机选择一个,那么在开始循环之前请先对键进行洗牌:

$keepKey = null;
$bestScore = -1;

$keys = array_keys($array); // <---
shuffle($keys);             // <
foreach($keys as $k) {      // <
    $v = $array[$k];        // <---
    $score = 0;
    if ($v[1] == 1 && $v[0] == 1) $score = 1;
    if ($v[1] == 2 && $v[0] >= 2) $score = 2;
    if ($v[1] == 3 && $v[0] >= 6) $score = 3;
    if ($v[1] == 4 && $v[0] >= 8) $score = 4;
    echo $score . "\n";       
    if ($score > $bestScore) {
        $keepKey = $k;
        $bestScore = $score;
    }
}

$sub_array = [$keepKey => $array[$keepKey]];