douchuanchai2793 2014-11-08 14:53
浏览 86
已采纳

PHP:如何从递归函数返回值的计数器?

function count($array){ 

    $counter=0;
    foreach($array as $key=>$value){ 
    if(is_array($value)){ 
            count($value); 
        }else{
            if(strcmp($value, "Hi") == 0){
                $counter++;
            }
        }
    }
}

$arrays = array("Hi", "a", "Hi", "b", "c", array("c", "Hi", array("Hi"), "d"));

If I call count($arrays); I want to print 4 in this case.
But my code keeps printing 0. It seems it does not return counter of "Hi" properly but I have no idea.

  • 写回答

1条回答 默认 最新

  • dtr32221 2014-11-08 14:55
    关注

    count() is a built-in function of PHP, better if you change the name:

    function myRecursiveCount($array, $needle = "Hi"){ 
       $counter=0;
       foreach($array as $value){ 
         if(is_array($value)){ 
           $counter += myRecursiveCount($value); 
         } else if ($value === $needle){
           $counter++;  
         }
       }
       return $counter;
    }
    
    $inputs = array("Hi", "a", "Hi", "b", "c", array("c", "Hi", array("Hi"), "d"));
    echo myRecursiveCount($inputs); // Prints 4
    

    You need two edits:

    • the function should return the $counter;
    • in the recursive call you should append the result: $counter += f();.

    I have also applied two optional improvements:

    • you don't need to populate the variable $key as you don't need it
    • to compare two strings you can simply use == comparison operator (strcmp feels so old)

    Live on codepad: http://codepad.org/ATiKV09d

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分