【问题标题】:How to count the inner array count too如何计算内部数组计数
【发布时间】:2015-08-17 11:41:45
【问题描述】:

我有一个类似 as 的数组

$arr[0] = 'summary';
$arr[1]['contact'][] = 'address1';
$arr[1]['contact'][] = 'address2';
$arr[1]['contact'][] = 'country';
$arr[1]['contact'][] = 'city';
$arr[1]['contact'][] = 'pincode';
$arr[1]['contact'][] = 'phone_no';
$arr[2]['work'][] = 'address1';
$arr[2]['work'][] = 'address2';
$arr[2]['work'][] = 'country';
$arr[2]['work'][] = 'city';
$arr[2]['work'][] = 'pincode';
$arr[2]['work'][] = 'phone_no';

使用 count($arr) 它返回 3 但我还需要计算内部数组值,因此它将返回 13

到目前为止我尝试过的是

function getCount($arr,$count = 0) {

    foreach ($arr as $value) {

        if (is_array($value)) {
            echo $count;
            getCount($value,$count);
        }
        $count = $count+1;
    }
    return $count;
}

echo getCount($arr);

但它没有按预期工作

【问题讨论】:

  • 如果您也想计算内部数组中的值(深度无关紧要),您可以将第二个参数作为count($your_array, COUNT_RECURSIVE) 传递给count。如果您只想计算数组的内部值,您可以从递归计数中减去正常计数。
  • @Andrew 这将返回17
  • 检查这个[多维数组计数][1][1]:stackoverflow.com/questions/9062770/…

标签: php arrays


【解决方案1】:

您可以为此使用array_walk_recursive。这可能会有所帮助 -

$tot = 0;
array_walk_recursive($arr, function($x) use(&$tot) {
    $tot++;
});

但它是一个递归函数,所以你需要小心。

getCount() 方法中,您不会将数组的计数存储在任何地方。所以每次调用$count 只会增加1

DEMO

【讨论】:

  • 但是我在foreach 循环中的代码中有错误,因为我可能也已经嵌套了数组。总之谢谢
  • 要修复您的原始功能,我认为您需要执行$count = getCount($value,$count); 或通过引用传递$count
【解决方案2】:

试试这个

function getCount($arr, $count = 0) {
    foreach ($arr as $value) {
        if (is_array($value)) {
            $count = getCount($value, $count);
        } else {
            $count = $count + 1;
        }
    }
    return $count;
}

echo getCount($arr);

您在这里所做的是您没有将值存储在任何变量中,这会导致您的代码出现问题,因为您正处于完美的状态

【讨论】:

    【解决方案3】:

    如果只需要统计前两层,可以做一个简单的foreach,不需要用到递归函数!:

    $count = 0;
    foreach( $bigArray as $smallArray ){
        if( is_array( $smallArray ) )
              $count += count( $smallArray );
        else
              $count ++;
    }
    

    【讨论】:

      【解决方案4】:

      也许我的方法很幼稚,但我只是使用了sizeof() 函数。该函数的文档显示它可以使用第二个参数1 来告诉函数递归地计算多维数组。

      因此,要获得“计数”,您可以简单地编写 sizeof($arr, 1);,它应该返回 13。

      我承认编写自己的函数的价值,但是这种内置的PHP方法不是很简洁地解决了问题吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        • 1970-01-01
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        • 2019-08-21
        • 1970-01-01
        相关资源
        最近更新 更多