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 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目