Home Backend Development PHP Tutorial How to convert a one-dimensional array into a three-layer nested tree structure using PHP?

How to convert a one-dimensional array into a three-layer nested tree structure using PHP?

Apr 01, 2025 am 09:00 AM
red

How to convert a one-dimensional array into a three-layer nested tree structure using PHP?

This article discusses how to efficiently convert PHP 1D arrays into three-layer nested tree structures. Given an array containing project name, model, and location information, the goal is to convert it into a tree structure, with the project name as a first-level node, the model as a second-level node and the location as a third-level node.

Initial array:

 $arr = [
    ['name' => "Project 1", 'model' => "Gold", 'location' => 'Suzhou'],
    ['name' => "Project 1", 'model' => "Silver", 'location' => 'Shanghai'],
    ['name' => "Project 2", 'model' => "Copper", 'location' => 'Beijing'],
    ['name' => "Project 2", 'model' => "Copper", 'location' => 'Shenzhen'],
];
Copy after login

Target tree structure:

 $target = [
    [
        'name' => "item 1",
        'child' => [
            ['model' => "Gold", 'child' => [['location' => 'Suzhou']]],
            ['model' => "Silver", 'child' => [['location' => 'Shanghai']]],
        ]
    ],
    [
        'name' => "Project 2",
        'child' => [
            ['model' => "Copper", 'child' => [['location' => 'Beijing'], ['location' => 'Shenzhen']]],
        ]
    ],
];
Copy after login

The previous solution was too complicated. We can use a simpler and easier to understand method to build a tree-like structure using loops and conditional judgments:

 $result = [];
foreach ($arr as $item) {
    $name = $item['name'];
    $model = $item['model'];
    $location = $item['location'];

    // Find or create project name node $nameIndex = array_search($name, array_column($result, 'name'));
    if ($nameIndex === false) {
        $result[] = ['name' => $name, 'child' => []];
        $nameIndex = count($result) - 1;
    }

    // Find or create model node $modelIndex = array_search($model, array_column($result[$nameIndex]['child'], 'model'));
    if ($modelIndex === false) {
        $result[$nameIndex]['child'][] = ['model' => $model, 'child' => []];
        $modelIndex = count($result[$nameIndex]['child']) - 1;
    }

    // Add location node $result[$nameIndex]['child'][$modelIndex]['child'][] = ['location' => $location];
}

print_r($result); // output the converted tree structure
Copy after login

This code first initializes an empty array $result . It then iterates over each item in the original array $arr . For each project, it looks for the presence of the corresponding project name and model node. If it does not exist, a new node is created. Finally, it adds the location information under the corresponding model node. This method is clearer and easier to maintain.

This approach avoids nested array_map and array_reduce , making it easier to understand and debug. It operates directly on arrays and is more efficient. Choose the method that suits your project and adjust the code according to actual conditions.

The above is the detailed content of How to convert a one-dimensional array into a three-layer nested tree structure using PHP?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

How to solve the problem of grandfather's background obstructing pseudo-elements when text gradient adds shadows? How to solve the problem of grandfather's background obstructing pseudo-elements when text gradient adds shadows? Apr 05, 2025 pm 05:36 PM

When adding shadows to text gradients, the solution to the grandfather background blocks pseudo-elements. When adding shadows to text gradients, pseudo-elements and absolute positioning are usually used to...

How to accurately realize the small label effect in the design draft on the mobile terminal? How to accurately realize the small label effect in the design draft on the mobile terminal? Apr 04, 2025 pm 11:36 PM

How to achieve the effect of small labels in the design draft on the mobile terminal? When designing mobile applications, it is common to find out how to accurately restore the small label effect in the design draft...

The difference in output results of console.log: Why do the same variables have different printing methods but different results? The difference in output results of console.log: Why do the same variables have different printing methods but different results? Apr 04, 2025 am 11:48 AM

In-depth discussion of the differences in console.log output in this article will analyze the reasons why the output results of console.log function in a piece of code are different. Code snippets involve URL parameter resolution...

See all articles