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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制