Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8683977
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T22:10:46+00:00 2026-06-12T22:10:46+00:00

I have a 2-dimensional PHP array which I need to turn in to a

  • 0

I have a 2-dimensional PHP array which I need to turn in to a tree. The ‘path’ value in each inner-array is the enumerated path to the current node. (I got this idea from Bill Karwin’s book on SQL Antipatterns).

So, the array that I am starting with looks something like this:

array(
[1] => array('name' => 'Animals', 'path' => '1/'),
[2] => array('name' => 'Birds', 'path' => '1/3/'),
[3] => array('name' => 'Cockatoos', 'path' => '1/3/5/'),
[4] => array('name' => 'Fish', 'path' => '1/2/'),
[5] => array('name' => 'Kookaburras', 'path' => '1/3/4/')
)

As you may have gathered, the index of the outer array is meaningless. I have simply ordered the inner arrays alphabetically on ‘name’ and PHP has assigned numeric indexes on the outer array.

As far as the ‘path’ value goes, the very last segement of each path is a pseudo-id for the node, i.e. Animals is node 1, Birds is node 3. You can see that the full path describes the route to the given node, e.g. ‘Cockatoos’ is parented by ‘Birds’, which is parented by ‘Animals’.

I want to keep the alphabetic order of the nodes, but group them by their parent. In other words, I want an array that looks something like this (in its natural order):

[1]         => 'Animals'
[1][3]      => 'Birds'
[1][3][5]   => 'Cockatoos'
[1][3][4]   => 'Kookaburras'
[1][2]      => 'Fish'

I plan to iterate over this recursively to print a visual representation of the tree.

In trying to transform from one type of array to another my approaches have used recursion, variable variables and regular expressions, but I keep running into road blocks.

Also, is there an SPL data structure or iterator that I should be thinking about?

Thanks alot!

EDIT: Sorry, should have mentioned that the depth of the tree is variable. The example above has three levels, but in reality there will be many more.

Kim

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T22:10:47+00:00Added an answer on June 12, 2026 at 10:10 pm

    This will work, no matter the depth of the tree, possible due to the use of the Eval() function (which stands for evaluate). But the sorting on alphabet is not working properly yet. Because the indexes of the parent arrays stay the same it gets mixed up. BUt atleast you can build a tree already 🙂

    <?php
    $a = array(
            array('name' => 'Animals', 'path' => '1/'), 
            array('name' => 'Birds', 'path' => '1/3/'), 
            array('name' => 'Eagles', 'path' => '1/3/3/'),
            array('name' => 'Cockatoos', 'path' => '1/3/5/'), 
            array('name' => 'Fish', 'path' => '1/2/'), 
            array('name' => 'Kookaburras', 'path' => '1/3/4/')
        );
    Iterate($a);
    $tree = Iterate($a);
    
    var_dump($tree);
    
    OneLevelDeeper($tree);
    var_dump($tree);
    
    function Iterate($ChildArray)
    {
        $TreeArray;
        foreach($ChildArray as $Key => $Value)
        {
            //echo $Key.': '.$Value['name']."\r\n";
            $exp = explode('/', $Value['path']);
            $path;
            foreach($exp as $int)
            {
                if($int != "")
                {
                    $path[] = $int;
                }
            }
    
            //Using Eval() function of PHP
            $BuildSourceToEvaluate = '$TreeArray';
            for($i=0; $i<(count($path)-1); $i++)
            {
                $BuildSourceToEvaluate .= '[$path['.$i.']]';
            }
            $BuildSourceToEvaluate .= '[] = $Value[\'name\'];';
            echo $BuildSourceToEvaluate."\r\n";
            Eval($BuildSourceToEvaluate);
            //print_r($path);
            /*
            switch(count($path))
            {
                case 0:
                break;
                case 1:
                    $TreeArray[] = $Value['name']; 
                    //$TreeArray[$path[0]] = $Value['name']; //Use this for unique paths and keeping hold of the last ID in the tree path
                    //$TreeArray[$path[0]][] = $Value['name']; //Use this for non-unique tree paths
                break;
                case 2:
                    $TreeArray[$path[0]][] = $Value['name']; 
                    //$TreeArray[$path[0]][$path[1]] = $Value['name']; //Use this for unique paths and keeping hold of the last ID in the tree path
                    //$TreeArray[$path[0]][$path[1]][] = $Value['name']; //Use this for non-unique tree paths
                break;
                case 3:
                    $TreeArray[$path[0]][$path[1]][] = $Value['name'];
                    //$TreeArray[$path[0]][$path[1]][$path[2]] = $Value['name']; //Use this for unique paths and keeping hold of the last ID in the tree path
                    //$TreeArray[$path[0]][$path[1]][$path[2]][] = $Value['name']; //Use this for non-unique tree paths
                break;
            }
            */
            unset($path);
        }
        return $TreeArray;
    }
    
    
    function OneLevelDeeper(&$a)
    {
        sort($a);
        foreach($a as $Key => $Value)
        {
            if(is_array($Value))
            {
                sort($a[$Key]);
                OneLevelDeeper($a[$Key]);
            }
        }
    }
    
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a multi-dimensional array, which basically consists of one sub-array for each year.
I have a multi-dimensional array with 4 entries in each value - (1st name,
I have an single-dimensional array of PHP objects. Each object has two attributes, one
I have a PHP function which populates a multi-dimensional array $client->getResponse() I want to
I have a multi dimensional array in PHP. $f = array('one' => array(*doesntmatter*), two
If I have a multi dimensional array in PHP like so... [0] => Array
Possible Duplicate: php multi-dimensional array remove duplicate I have an array like this: $a
I have an multi-dimensional array that I want to send to a PHP script
I have to send a two-dimensional JavaScript Array to a PHP page. Indeed, I'm
I have several situations where I need to pass multi-dimensional PHP arrays into Javascript/jQuery.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.