0

我有 2 个数组:

首先:

$array1 = ("Key 1","Key 2","Key 3"); //is dynamic, so can range from 1 => many values

第二个数组是一个数据库值,它将根据玩家在库存中拥有的键数返回一个数组。

$array2 = ("Key 1","Key 1","Key 2","Key 3","Key 3","Key 3") //in this case, the player DOES have all the keys.

我的问题是,我想不出合适的逻辑来比较这些数组,$array2看看$array1.

我试过的比较代码..

$check = array();
while ($k = mysql_fetch_array($array2)) {
    foreach ($array1 as $name) {
    if ((string)$name == (string)$k['name']) $check[] = true;
    else $check[] = false;
    }
}
foreach ($check as $bool) {
    if ($bool == false) {
        $return = false;
    } else {
    $return = true;
    }
}
return $return;

问题是当 I 时print_r($check),我得到很多错误,所以即使播放器包含所有正确的键,关闭比较也会破坏代码并返回错误。

任何有关此比较逻辑的帮助都会非常好,如果您需要更多详细信息,请告诉我。

4

2 回答 2

0

答案是,这是in_array()我用来解决它的算法(感谢你们的帮助)

while ($k = mysql_fetch_array($pkey)) { //turn returned list of player items into a new array
    $new_pkey[] = $k['name'];
}
foreach ($key as $name) { //search new array using the set list required to pass the check
    if (in_array($name,$new_pkey)) $check[] = true;
    else $check[] = false;
}
foreach ($check as $bool) { //search the check array to see if it contains a false. If so, break and return false
    if ($bool == false) {
        $return = false;
        break; //crucial bug -- would return true unless the last element was false. This lets any element be false and finally yield false
    } else {
        $return = true;
    }
}
return $return;
于 2013-01-02T10:15:22.777 回答
0

你原来的逻辑是好的。你犯了两个错误:

  1. 您忘记在遇到真条件时跳出循环,以便循环继续并在下一次迭代时将 $check 设置为 false 并且这会导致 $check 不必要的膨胀。
  2. 您过早地将 $check 设置为 false;未来的匹配条件将翻转数组中另一个位置的位,而先前的不匹配已经将位设置为假。

试试这个:

<?php

$check = array();
foreach ($array1 as $name) {
    $check[$name] = false;
}

while ($k = mysql_fetch_array($array2)) {
    foreach ($array1 as $name) {
    if ((string)$name == (string)$k['name'])
    {
        $check[$name] = true;
        break;
    }
    }
}
foreach ($check as $bool) {
    if ($bool == false) {
    $return = false;
    } else {
    $return = true;
    }
}
return $return;
?>

然后你也可以做一些优化。无需比较从 DB 读取的每个值与 $array1 中的每个值,您可以仅针对 $check 数组中存在错误的键检查值。当你开始用 true 填充 $check 时,你的内部循环会运行得更快。

或者,如果您的内部循环较长,您可以考虑对其进行排序,以便搜索变得更快。我缺少内置的二进制搜索功能,或者 PHP 没有内置的;你可能需要从某个地方剪切和粘贴它。

或者,如果不进行优化,至少通过一次调用诸如“in_array”之类的函数来取消内部循环。

于 2013-01-02T10:16:03.550 回答