php 使用指定键名的COUNT_RECURSIVE?

jdg4fx2g  于 2023-05-12  发布在  PHP
关注(0)|答案(1)|浏览(1359)

count($arr['children'], COUNT_RECURSIVE);来获取原始children键中的键的总数,但是我想过滤掉除了名为'children'的键之外的所有键。我不确定count_recursive是这样工作的。

$arr =  array (
    'id' => '81',
    'parent' => NULL,
    'children' =>
        array (
          0 =>
          array (
            'id' => '173',
            'parent' => '81',
          ),
          1 =>
          array (
            'id' => '84',
            'parent' => '81',
            'children' =>
            array (
              0 =>
              array (
                'id' => '85',
                'parent' => '84',
                'children' =>
                array (
                  0 =>
                  array (
                    'id' => '131',
                    'parent' => '85',
                    'children' =>
                    array (
                      0 =>
                      array (
                        'id' => '176',
                        'parent' => '131',
                      ),
                    ),
                  ),
                ),
              ),
              1 =>
              array (
                'id' => '174',
                'parent' => '84',
              ),
              2 =>
              array (
                'id' => '175',
                'parent' => '84',
              ),
            ),
          ),
    ),
);

echo count($arr['children'], COUNT_RECURSIVE);

我试图让它返回7,但因为它计算所有键,它返回24。我怎么能这么做

5tmbdcev

5tmbdcev1#

我在战斗之后已经走了很长的路,但是如果你仍然想复制和粘贴一个算法来回答这个问题“如何递归地计算这个数组中本身是数组但其键不是'children'的元素”,这里有一个可以完成这项工作并给出预期的“7”作为结果:

function countAllArraysButKey(array $array, int|string $but_key) : int
{
    $count = 0;
    foreach ($array as $key => $value) {
        if (!is_array($value)) {
            continue;
        }
        $count += countAllArraysButKey($value, $but_key);
        if ($key !== $but_key) {
            $count ++;
        }
    }
    return $count;
}

echo 'count: ' . count($arr['children'], COUNT_RECURSIVE) . "\n";
echo 'countAllArraysButKey: ' . countAllArraysButKey($arr['children'], 'children') . "\n";

玩得开心!

相关问题