Home >Backend Development >PHP Problem >Share a PHP-based tree array modification method

Share a PHP-based tree array modification method

PHPz
PHPzOriginal
2023-04-26 14:22:43519browse

In daily development, we often encounter the need to modify a certain value in a tree array. How to deal with this situation? This article will share a PHP-based tree array modification method.

First of all, we need to understand what a tree array is. A tree structure refers to a data structure with hierarchical relationships, in which each node can have zero or more child nodes, and there can also be hierarchical relationships between child nodes. In PHP, we can use a two-dimensional array to represent a tree structure, in which each child node can be an array with the subscript "children".

The following is an example of a tree structure represented by a two-dimensional array:

$data = [
    [
        'id' => 1,
        'name' => 'A',
        'children' => [
            [
                'id' => 2,
                'name' => 'B',
                'children' => [
                    [
                        'id' => 3,
                        'name' => 'C',
                        'children' => [
                            [
                                'id' => 4,
                                'name' => 'D',
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];

Next, let's simulate a requirement: change the name field of the node with id 3 to 'E'.

First, we need to traverse the entire tree, find the node with id 3 recursively, and then modify the value of its name field. The following is the code implemented based on this idea:

function modifyNodeValue(&$data, $id, $fieldName, $newValue)
{
    foreach ($data as &$node) {
        if ($node['id'] == $id) {
            $node[$fieldName] = $newValue;
        }
        if (!empty($node['children'])) {
            modifyNodeValue($node['children'], $id, $fieldName, $newValue);
        }
    }
}

The above function uses reference passing and can directly modify the original array. We pass in the parameters id, fieldName, and newValue to specify which field of which node is to be modified to what value. The actual implementation is to traverse each node of the array, and when the node with the specified id is found, modify the value of its specified field.

It should be noted here that due to the need for recursive traversal, this method can easily time out or exceed the memory limit when the tree structure is relatively large, so it is not suitable for processing very large tree structures. It can be optimized by dividing the large tree structure into multiple small tree structures, then modifying them separately, and finally merging them.

Next, let’s take a look at how to call the above function to complete our example requirements.

// 修改id为3的节点的name字段为'E'
modifyNodeValue($data, 3, 'name', 'E');
// 输出修改后的树型结构
print_r($data);

After executing the above code, you can get the following output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => A
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [name] => B
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 3
                                            [name] => E
                                            [children] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [id] => 4
                                                            [name] => D
                                                            [children] => Array
                                                                (
                                                                )
                                                        )
                                                )
                                        )
                                )
                        )
                )
        )
)

As you can see, we have successfully modified the name field of the node with id 3 to 'E', while maintaining The structure of the entire tree remains unchanged.

To sum up, the above is a tree array modification method based on PHP. In actual development, we can choose different optimization methods according to specific needs and the size of the data to achieve more efficient processing.

The above is the detailed content of Share a PHP-based tree array modification method. 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