Home > Backend Development > PHP Problem > How to implement tree structure in php array

How to implement tree structure in php array

PHPz
Release: 2023-04-27 10:28:46
Original
1353 people have browsed it

PHP is a widely used server-side scripting language mainly used for web development. During the development process, we often need to use tree-structured data to display certain data or module relationships. At this time, arrays in PHP can come in handy. This article will introduce how to use PHP arrays to implement a tree structure.

1. What is a tree structure?

Tree structure is a very common data structure, which is composed of nodes and edges. Each node represents an object, such as a file or folder in a web page, chapters and sections in a book, multiple departments in a company, and so on. The edges between nodes represent the relationships between these objects, such as the inclusion relationship between folders and files, and the hierarchical relationship between chapters and sections.

In a tree structure, each node has only one parent node, but can have multiple child nodes. The parent node is a node that is higher than the current node in the tree structure, and the child node is a node that is lower than the current node in the tree structure. This relationship forms a hierarchical structure, as shown in the figure below.

2. PHP array implements tree structure

In PHP, we usually use arrays to store tree-structured data. Arrays are a very convenient data type in PHP that can store different types of data and each element can be quickly accessed using subscripts. Using arrays to store tree-structured data can make the code more concise and easier to maintain.

The following is a sample code that uses a PHP array to implement a tree structure:

<?php
/**
 * 将一个数组转换成树形结构
 * @param array $arr 需要转换的数组
 * @param int   $parentId 父节点ID
 * @return array 转换后的树形结构数组
 */
function arrayToTree($arr, $parentId = 0) {
    $tree = array();
    foreach ($arr as $key => $value) {
        if ($value['parent_id'] == $parentId) {
            unset($arr[$key]);
            $value['children'] = arrayToTree($arr, $value['id']);
            $tree[] = $value;
        }
    }
    return $tree;
}

// 示例数组
$arr = array(
    array('id' => 1, 'name' => '节点1', 'parent_id' => 0),
    array('id' => 2, 'name' => '节点2', 'parent_id' => 1),
    array('id' => 3, 'name' => '节点3', 'parent_id' => 1),
    array('id' => 4, 'name' => '节点4', 'parent_id' => 2),
    array('id' => 5, 'name' => '节点5', 'parent_id' => 2),
    array('id' => 6, 'name' => '节点6', 'parent_id' => 3),
    array('id' => 7, 'name' => '节点7', 'parent_id' => 3)
);

// 将数组转换成树形结构
$tree = arrayToTree($arr);

// 输出树形结构
print_r($tree);
Copy after login

In the above code, we define a arrayToTree function to convert an Convert the array into a tree structure. The function accepts two parameters: the array to be converted and the parent node ID. When the parent node ID is 0, it means that the root node needs to be obtained and the entire array converted into a tree structure. If the parent node ID is not 0, its child tree structure is converted.

We use foreach to loop through each element in the array, and if the parent_id value of the current element is equal to the parent node ID to be found, add it to the current In the node's children array. At the same time, we delete the added elements from the original array so that they are not added repeatedly during the next loop.

Finally, we return the converted tree structure array and use the print_r function to output its contents.

3. Summary

In this article, we introduced how to use PHP arrays to implement tree structures. By defining a processing function, we can convert any two-dimensional array into a tree-structured array with hierarchical relationships, which is convenient for us to use during the development process.

Of course, there is more than one way to implement a tree structure, and using PHP arrays is only one of them. In actual development, we need to choose the most appropriate way to process data according to the specific situation in order to improve code quality and development efficiency.

The above is the detailed content of How to implement tree structure in php array. 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