Home  >  Article  >  Backend Development  >  How to convert a two-dimensional array in PHP to a specified key value

How to convert a two-dimensional array in PHP to a specified key value

PHPz
PHPzOriginal
2023-04-27 09:03:58779browse

The two-dimensional array in PHP is a very common data structure that can be used to store large amounts of data and is very flexible. Usually, when we process a two-dimensional array, we need to filter out specific elements based on certain conditions or reorganize the structure of these elements. In this case, converting the 2D array into another form can be very useful. This article will introduce how to use the array function in PHP to convert a two-dimensional array into a specified key value form.

1. What is a two-dimensional array

A two-dimensional array is a data structure composed of several one-dimensional arrays. It can be thought of as a table, with each row representing a one-dimensional array and the columns representing elements in the one-dimensional array.

For example, the following code creates a two-dimensional array:

$data = array(
    array("name" => "Tom", "age" => 20),
    array("name" => "Jerry", "age" => 18)
);

This array contains two elements, each element is a one-dimensional array containing "name" and "age" Two keys and corresponding values. This two-dimensional array can represent the name and age information of a group of people.

2. Two-dimensional array conversion

  1. Convert one-dimensional array into key-value pairs

Before processing the two-dimensional array, let us first look at Let's see how to convert a one-dimensional array into the form of specified key-value pairs. PHP provides a very practical function array_column() to implement this function. The array_column() function can remove a specified column from a multidimensional array and return the value of the column. For example:

$data = array(
    array("name" => "Tom", "age" => 20),
    array("name" => "Jerry", "age" => 18)
);

$names = array_column($data, "name");
print_r($names);

Output:

Array
(
    [0] => Tom
    [1] => Jerry
)

In the above code, we use the array_column() function to extract the "name" column in the $data array and store it in a new in the array $names. In this way, we can easily obtain all the name information.

  1. Convert the two-dimensional array into the specified key value form

In actual development, we usually need to organize the two-dimensional array according to different conditions, such as age Categorize, or sort by initials, etc. At this time, we can use the array function in PHP to achieve this goal. Below we will introduce several commonly used methods.

(1) Use the array_reduce() function

The array_reduce() function can perform cumulative calculations on all elements in the array and return the result. By using this function, we can combine elements in a two-dimensional array according to the specified key value.

For example, if we want to classify the above $data array according to the "age" value, we can use the following code:

$result = array_reduce($data, function ($acc, $item) {
    $age = $item['age'];
    if (!isset($acc[$age])) {
        $acc[$age] = array();
    }
    $acc[$age][] = $item;
    return $acc;
}, array());

print_r($result);

Output:

Array
(
    [20] => Array
        (
            [0] => Array
                (
                    [name] => Tom
                    [age] => 20
                )

        )

    [18] => Array
        (
            [0] => Array
                (
                    [name] => Jerry
                    [age] => 18
                )

        )

)

In the above code , we used PHP anonymous functions and array_reduce() function. The first parameter $acc of the anonymous function represents the accumulator, which is used to store the accumulated results, and the second parameter $item represents each element in the array. In the function body, we first get the "age" value of the element, and then determine whether the array corresponding to the "age" value already exists in the accumulator. If it does not exist, create a new array; finally, add the element to in this array.

(2) Use the array_map() function

The array_map() function can process each element in the array and return a new array. By using this function, we can modify the elements in the two-dimensional array according to the specified key value.

For example, the following code changes the "name" key value of each element in the $data array above to the "age" value of the element and stores it in a new array:

$result = array_map(function ($item) {
    $age = $item['age'];
    $item['name'] = $age;
    return $item;
}, $data);

print_r($result);

Output:

Array
(
    [0] => Array
        (
            [name] => 20
            [age] => 20
        )

    [1] => Array
        (
            [name] => 18
            [age] => 18
        )

)

In the above code, we used the PHP anonymous function and array_map() function. The parameter $item of the anonymous function represents each element in the array. In the function body, we first get the "age" value of the element and then assign that value to the "name" key of the element.

3. Summary

The above is the method of converting a two-dimensional array in PHP into a specified key value. To summarize:

  1. Use the array_column() function to convert Converts a one-dimensional array into the form of specified key-value pairs.
  2. Use the array_reduce() function to combine two-dimensional arrays according to specified key values.
  3. Use the array_map() function to modify the elements in the two-dimensional array according to the specified key value.

In actual development, we can choose appropriate methods to process elements in two-dimensional arrays to meet different business needs.

The above is the detailed content of How to convert a two-dimensional array in PHP to a specified key value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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