doulu6314 2014-11-29 02:43
浏览 134
已采纳

如何使用for循环逐元素地比较两个数组?

This is a mock example of my problem.

The 'for loops' will be contained inside a while loop, if that matters.

The code below should compare every element of each array and echo out the element that is the same. In this case 'Fat'.

However, the code is not working and I can't figure out why. I'm sure it's a simple fix, but I can't seem to find it.

$searchValue="Bob Is Fat";
$explode = explode(' ', $searchValue);           //turns $searchValue into an array
$tags_cnt = count($explode);                     //counts elements in the array

$result_tag = array("Volvo", "Skinny", "Fat");   //creates an array
$row_cnt = count($result_tag);                   //counts elements in array


        for($i=0; $i<$tags_cnt-1; $i++) {
            for($x=0; $x<$row_cnt-1; $x++) {
                if ($result_tag[$x] == $explode[$i]) {        
                    echo $explode[$i];
                }   
            } //2 forloop                                                               
        } //1 forloop
  • 写回答

3条回答 默认 最新

  • dsadsadsa1231 2014-11-29 02:46
    关注

    Remove the -1, the value of $tags_cnt-1 is 2, when start the for the value $i is 0, in the second loop the value for the $i is 1, the condition says that the loop works until $i<$tags_cnt so, in the second loop 1<2 and is the last one because in the next loop don't match with the condition.

    <?php
    $searchValue="Bob Is Fat";
    $explode = explode(' ', $searchValue);           //turns $searchValue into an array
    $tags_cnt = count($explode);                     //counts elements in the array
    
    $result_tag = array("Volvo", "Skinny", "Fat");   //creates an array
    $row_cnt = count($result_tag);                   //counts elements in array
    
    
            for($i=0; $i<$tags_cnt; $i++) {
                for($x=0; $x<$row_cnt; $x++) {
                    if ($result_tag[$x] == $explode[$i]) {        
                        echo $explode[$i];
                    }   
                } //2 forloop                                                               
            } //1 forloop
    ?>
    

    Or in your first for:

    for($i=0; $i<=$tags_cnt-1; $i++)
    

    and in the second:

    for($x=0; $x<=$row_cnt-1; $x++)
    

    Hope works for you.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line