How to specifically count arrays inside of an array?

$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]

输出应该是3.

推荐答案

可以使用递归函数来实现这一点.我举个例子:

<?php

$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ];

$arrayCount = 0; # this variable will hold count of all arrays found

# Call a recursive function that starts with taking $array as an input
# Recursive function will call itself from within the function
countItemsInArray($array);


function countItemsInArray($subArray) {

    # access $arrayCount that is declared outside this function
    global $arrayCount;
    
    # loop through the array. Skip if the item is NOT an array
    # if it is an array, increase counter by 1
    # then, call this same function by passing the found array
    # that process will continue no matter how many arrays are nested within arrays
    foreach ($subArray as $x) {
        if ( ! is_array($x) ) continue;

        $arrayCount++;
        countItemsInArray($x);
    }

}


echo "Found $arrayCount arrays\n";

Example

https://rextester.com/SOV87180

Explanation

下面是函数的运行方式.

  • [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]被发送到countItemsInArray函数
  • 此函数用于查看数组中的每个项
  • 第10部分是回顾.它不是数组,所以函数转到下一项
  • 《你好》已经被 comments 过了.它不是数组,所以函数转到下一项
  • [1,2,3,['hi',7]]被判断.它是一个数组,所以arrayCount增加到1,并调用相同的函数,但现在该函数的输入是[1, 2, 3, ['hi', 7].

记住,用整个数组调用的同一个函数不是死函数.它只是在等待这countItemsInArray([1, 2, 3, ['hi', 7]])件事的完成

  • 1.进行判断.它不是数组,因此下一项将被计算
  • 2.判断...
  • 3.判断...
  • [hi',7]被判断.它是一个array.因此,数组计数增加到2
  • countItemsInArray(['hi', 7]).

请记住,参数为AND countItemsInArray([1,2,3,['hi',7]])的countItemsInArray(完整数组)现在正在等待countItemsInArray(['hi', 7])的完成

  • hi被判断.这不是数组,所以函数测试下一项
  • 7.进行判断.这也不是array.因此,该函数完成后,将控制权返回到countItemsInArray([1, 2, 3, ['hi', 7]])

countItemsInArray([1, 2, 3, ['hi', 7]])认识到它没有什么可判断的了.控件返回给countItemsInArray($array).

  • [15,67]进行了判断.它是一个数组,所以数组计数增加到3
  • 调用countItemsInArray([15,67]),它计算15和16,并确定它们都不是数组,因此它将控制权返回给countItemsInArray($array)

countItemsInArray($array)计算12并确定它也不是array.所以,它结束了它的工作.

然后,echo回声显示数组计数为3.

Php相关问答推荐

从产品中获取WooCommerce产品属性单选按钮的列表WP_Query

过滤WooCommerce管理员订单列表(+HPOS)中包含其作者产品的订单

WooCommerce基于元数据的自定义范围目录排序

如何修复条带元素中的错误&&客户端_机密&

在Laravel Eloquent中实现一对多关系

获取并判断WooCommerce用户订阅结束日期

使用php ZipArhive类将Zip压缩文件分成多个部分

fpm-php + nginx + POST数据

在WooCommerce上设置简单和可变产品的最小订单量

无额外字段的Laravel同步

扩展 WooCommerce 类触发未捕获错误:未找到WC_Coupon类

htaccess 配置提供静态文件和动态文件

当未 Select 任何变体时,在 WooCommerce 可变产品上显示自定义文本

Laravel 10 中的自定义类未找到

如何在 Phpunit 的静态提供程序中创建测试双打?

将图像作为 PHP post 响应发送到浏览器

无法读取某些 WordPress 主机上的 cookie

跟踪通过 WooCommerce 分层定价表插件进行的购买

正则表达式请帮我从内容中找到这个词

如果 static:: 被解析为B,为什么 PHP 会执行A的方法