Home > Backend Development > PHP Problem > How to determine the dimensions of an array in php

How to determine the dimensions of an array in php

PHPz
Release: 2023-04-27 09:20:23
Original
1129 people have browsed it

In PHP, array is one of the most common data types. Through arrays, you can combine a set of data in a certain way to facilitate our data operation and management. The dimensions of an array are a way for us to classify and describe arrays.

In PHP, the dimensions of an array are described based on the nested structure of the array elements. If an array contains only a single element, the dimension of the array is 1, for example:

$arr = array(1, 2, 3, 4);
echo count($arr); // 输出 4
Copy after login

The above array contains only a single element, so its dimension is 1 and the length of the array is 4.

If an array contains other array elements, the dimension of the array becomes the number of levels containing the nested array. For example:

$arr2 = array(
    1, 
    array(
        2, 
        array(3, 4), 
        5
    ),
    6,
    array(7, 8)
);
echo count($arr2); // 输出 4
Copy after login

The above array contains two nested arrays, so its dimension is 2 and the length of the array is 4.

So how to determine the dimensions of an array? Here are several methods:

1. Use recursion to determine the dimensions of an array

Recursion is an idea widely used in computer science, which can process multi-layer nested data. . We can use recursion to determine the dimension of the array. The code is as follows:

// 递归计算数组维度
function getDimension($arr)
{
    if (!is_array($arr)) {
        return 0;
    } else {
        $max = 0;
        foreach ($arr as $subArr) {
            $subArrDimension = getDimension($subArr);
            if ($subArrDimension > $max) {
                $max = $subArrDimension;
            }
        }
        return $max + 1;
    }
}
Copy after login

The above functiongetDimension($arr) can accept any array and calculate the dimension of the array recursively. . Among them, is_array($arr) is used to determine whether the element is an array type. If it is not an array type, 0 is returned, indicating that the dimension of the element is 0. If it is an array type, iterate over the array elements, recursively calculating the dimensions of its subarrays each time, and finally return the largest dimension in the subarray.

2. Use nested foreach to determine the dimensions of the array

In fact, we can also determine the dimensions of the array through nested foreach loops. If all elements of an array are not of array type, its dimension is 1; if it contains elements of array type, its dimension is equal to the dimension of the innermost subarray plus 1. The code is as follows:

// 使用 foreach 嵌套计算维度
function getDimension2($arr)
{
    if (!is_array($arr)) {
        return 0;
    } else {
        $depth = 1;
        foreach ($arr as $subArr) {
            if (is_array($subArr)) {
                $subArrDepth = getDimension2($subArr) + 1;
                if ($subArrDepth > $depth) {
                    $depth = $subArrDepth;
                }
            }
        }
        return $depth;
    }
}
Copy after login

The above code defines the function getDimension2($arr), its calculation method is the same as getDimension($arr), but using nesting The foreach loop. Among them, if an element is not an array type, 0 is returned directly; if it is an array type, each element is traversed, the dimension of the innermost subarray is calculated, and then 1 is added to it.

3. Use the array_filter function to determine the dimensions of the array

PHP built-in function array_filter() can be used to filter elements in the array that do not meet the conditions and return them based on the filtering results a new array. We can use this to determine the dimensions of the array. The code is as follows:

// 使用 array_filter 函数计算维度
function getDimension3($arr)
{
    if (!is_array($arr)) {
        return 0;
    } else {
        $child = current($arr);
        $notEmpty = array_filter($arr);
        if (count($notEmpty) == 0) {
            return 1;
        } else {
            return is_array($child) ? getDimension3($child) + 1 : 1;
        }
    }
}
Copy after login

The above code defines the function getDimension3($arr), which uses the array_filter() function. Among them, use current($arr) to take out the first element in the array and determine whether the element is of array type. If it is not an array type, it means that the dimension of the array is 1; if it is an array type, use array_filter($arr) to filter out all empty elements in the array, and based on the returned new The length of the array is used to determine the dimensions of the array.

4. Use the str_repeat function to determine the dimension of the array

Another simple method is to determine the dimension of the array through the change in string length. Here we use the str_repeat function. The specific implementation is as follows:

// 使用 str_repeat 函数计算维度
function getDimension4($arr)
{
    $temp = $arr;
    $i = 0;
    while (is_array($temp)) {
        $temp = current($temp);
        $i++;
        $str = str_repeat('.', $i);
        echo '<pre class="brush:php;toolbar:false">'.$str.implode($str, $temp).'
';     }     return $i; }
Copy after login

The above code defines the function getDimension4($arr), which uses the current() function and str_repeat( ) function. Use a while loop inside the function to continuously traverse the nested subarrays in the array, print out a spaced string each time it traverses, and finally return the value of i.

The above are several ways to determine the dimensions of an array, among which recursive and foreach implementation methods are more commonly used. Developers can choose to use different methods to implement it according to the actual situation.

The above is the detailed content of How to determine the dimensions of an array in php. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template