如何计算每个循环内的键?

时间:2016-04-30 09:46:17

标签: php

    function findKey($array, $keySearch) {
        $count = 0;
        foreach ($array as $key => $item) {
            if (stripos($key, $keySearch) !== false){
            $count++;
            echo "<li>".$key."</li>";
                }
            if (is_array($item)){
               findKey($item, $keySearch); 
            }
        } 
        echo "Total number of keys: ".$count;       
    }

echo findKey($array, $keySearch);

我尝试计算每个循环中的密钥。但我的结果是

  • 香蕉
  • 苹果
  • 密钥总数:0010101000

    我做错了什么?

    1 个答案:

    答案 0 :(得分:2)

       function findKey($array, $keySearch) {
            global $count;
            foreach ($array as $key => $item) {
                if (stripos($key, $keySearch) !== false){
                $count++;
                echo "<li>".$key."</li>";
                    }
                if (is_array($item)){
                   findKey($item, $keySearch); 
                }
            } 
        }
    
    $count = 0;
    findKey($array, $keySearch);
    echo "Total number of keys: ".$count;