doutuanxiao4619 2015-08-25 08:42
浏览 186
已采纳

如何使用for循环比较两个数组?

I have 2 explode arrays from the database. and this is what i did.

    $searches = explode(',', $searchengine);
    $icons = explode(',', $icon);
    $b = count($searches);
    $c = count($icons);

I also made an array to compare each explode array to.

$searchesa = array("google","yahoo","bing");
    $d = count($searchesa);
    $iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo");
    $y = count($iconsa);

Then i used for loops to travel to different array indexes. But the result is wrong, and sometimes I have an error which says UNDEFINED OFFSET.

for ($a=0; $a <$d ; $a++) {
    if ($searches[$a] == $searchesa[$a]) 
            {echo '<br>'.$searchesa[$a].': check ';
        }else
        echo '<br>'.$searchesa[$a].': chok ';
    }

for ($x=0; $x <$y ; $x++) {
    if ($icons[$x] == $iconsa[$x]) 
        echo '<br>'.$iconsa[$x].': check ';
    else
        echo '<br>'.$iconsa[$x].': chok ';
}

If the index from the database and the array I made are the same, it will state check, else it will state chok.

  • 写回答

4条回答 默认 最新

  • dongshai1944 2015-08-25 08:56
    关注

    I posted this in my comment, but I suppose the outline will work better in an answer.

    I hope this could be of any help:

    <?php
    $array_a = ['test','test2']; // assume this is your first array
    $array_b = ['test']; // assume this is the array you wan to compare against
    $found = false;
    
    foreach ($array_a as $key_a => $val_a) {
        $found = false;
        foreach ($array_b as $key_b => $val_b) {
           if ($val_a == $val_b) {
                echo '<br>'. $val_b .': check ';     
                $found = true;
            }     
        }
        if (!$found)
            echo '<br>'. $val_a .': chok ';
    }
    ?>
    

    EDIT: Please excuse me for not testing it.

    This thing will loop through the first array, and compare it with every value in the other array.

    Tip: You can easily put this in a function and call it like compare($arr1, $arr2)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题