Home > Backend Development > PHP Problem > How to get the first number of elements of multi-dimensional array in php

How to get the first number of elements of multi-dimensional array in php

PHPz
Release: 2023-04-26 09:34:00
Original
881 people have browsed it

PHP is a popular open source server-side scripting language widely used in the field of web development. The array in PHP is a very powerful data structure that supports multi-dimensional arrays and can be used to store and process complex data types. In actual development, we often need to operate on multi-dimensional arrays, for example, taking out the first few elements of the array.

In PHP, we can use multiple built-in functions to operate on multi-dimensional arrays. Below, I will introduce some common methods to achieve the function of removing the first few elements of a multi-dimensional array.

Method 1: Use the array_slice function

The array_slice function can remove a continuous element from an array and return a new array composed of these elements. Its syntax is as follows:

array array_slice ( array $array , int $offset , int|null $length = null , bool $preserve_keys = false )
Copy after login

Among them, $array represents the original array to be operated; $offset represents the position from which to start taking the value, which can be a negative number, indicating the last element from the end of the array to start taking the value; $length indicates the number of elements to be retrieved, which can be null, which indicates that all elements from $offset to the end of the array are retrieved; $preserve_keys indicates whether to retain the key names of the original array. The default is false, which means not to retain.

The following is a sample code that uses the array_slice function to remove the first few elements of a multi-dimensional array:

function array_multi_slice($array, $count) {
    //计算数组的总长度
    $total = count($array, COUNT_NORMAL);
    //如果要取出的元素个数小于等于总长度,则直接通过array_slice函数取值
    if($count <= $total) {
        return array_slice($array, 0, $count, true);
    }
    //否则,需要遍历二维数组取值
    $result = array();
    foreach($array as $key => $value) {
        if($count == 0) break;
        if(is_array($value)) {
            //如果是二维数组,则递归调用array_multi_slice函数取值
            $temp = array_multi_slice($value, $count);
            foreach($temp as $k => $v) {
                $result[$key][$k] = $v;
            }
            $count -= count($temp, COUNT_NORMAL);
        } else {
            //如果是普通数组,则直接取值
            $result[$key] = $value;
            $count--;
        }
    }
    return $result;
}
Copy after login

In this code, we first calculate the total length of the array $total. If we want If the number of elements taken out, $count, is less than or equal to $total, just use the array_slice function to get the value and return the result. Otherwise, we need to traverse the two-dimensional array to get values.

When traversing a two-dimensional array, we first determine whether the current element $value is a two-dimensional array. If so, recursively call the array_multi_slice function to retrieve the value and store the result in the $result array; if not, Then store the element directly in the $result array. During the traversal process, we need to continuously reduce the value of $count until the desired number of elements is taken out.

Method 2: Use the array_chunk function

The array_chunk function can divide an array into multiple blocks according to the specified size. Each block forms a new array and returns a two-dimensional array. Its syntax is as follows:

array array_chunk ( array $array , int $size , bool $preserve_keys = false )
Copy after login

Among them, $array represents the original array to be operated; $size represents the size of each block; $preserve_keys represents whether to retain the key name of the original array. The default is false, which means not to retain it. .

The following is a sample code that uses the array_chunk function to remove the first few elements of a multi-dimensional array:

function array_multi_chunk($array, $count) {
    $temp = array();
    foreach($array as $key => $value) {
        if(is_array($value)) {
            //如果是二维数组,则递归调用array_multi_chunk函数分割
            $result = array_multi_chunk($value, $count);
            foreach($result as $k => $v) {
                if(!isset($temp[$k])) {
                    $temp[$k] = array();
                }
                $temp[$k] += $v;
            }
        } else {
            //如果是普通数组,则直接存储
            $temp[(int)($key/$count)][$key] = $value;
        }
    }
    return $temp;
}
Copy after login

In this code, we first traverse the two-dimensional array. If the current element $value is If it is a two-dimensional array, call the array_multi_chunk function recursively to split it, and store the result in the $temp array; if it is a normal array, store it directly in the $temp array. When storing array elements, we determine which block the element belongs to by calculating $key/$count, and store it in the corresponding array.

Finally, we return the $temp array. It should be noted that when splitting a two-dimensional array, since the number of elements in each sub-array is not necessarily equal, the length of each sub-array may be different.

To sum up, we can use the array_slice function or array_chunk function to take out the first few elements of the multi-dimensional array. The specific method selection should be determined based on the actual situation.

The above is the detailed content of How to get the first number of elements of multi-dimensional 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