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条)

报告相同问题?

悬赏问题

  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 vscode platformio
  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开