Home > Backend Development > PHP Tutorial > How to Build a Tree Structure from a Flat Array in PHP?

How to Build a Tree Structure from a Flat Array in PHP?

Susan Sarandon
Release: 2024-11-26 20:13:16
Original
231 people have browsed it

How to Build a Tree Structure from a Flat Array in PHP?

Build a Tree from a Flat Array in PHP

A common task when working with hierarchical data structures is to convert a flat array into a tree-like structure. This can be done by identifying parent-child relationships and nesting elements accordingly.

One way to approach this is to iterate through the array and examine each element's parent_id value. If an element's parent_id is zero, it is considered a root level item. For other elements, their parent_ids can be used to determine their hierarchy within the tree.

To preserve the original array, it is recommended to create copies of elements as they are added to the tree. This can be achieved using the array_values() function.

Here's an example implementation:

function buildTree(array &$elements, $parentId = 0) {
  $branch = array();

  foreach ($elements as $element) {
    if ($element['parent_id'] == $parentId) {
      $children = buildTree($elements, $element['id']);
      if ($children) {
        $element['children'] = $children;
      }
      $branch[] = $element;
    }
  }

  return $branch;
}
Copy after login

To prevent duplicate elements in the resulting tree, it is crucial to unset the processed elements from the original array. This can be done by adding a line of code within the loop:

unset($elements[$element['id']]);
Copy after login

Using this revised function, the flat array can be converted into a hierarchical tree structure. The result will be an array with nested child elements under each parent element.

The above is the detailed content of How to Build a Tree Structure from a Flat 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template