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 8169067
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T20:44:05+00:00 2026-06-06T20:44:05+00:00

Possible Duplicate: Converting an array from one to multi-dimensional based on parent ID values

  • 0

Possible Duplicate:
Converting an array from one to multi-dimensional based on parent ID values

I am working in PHP.

I have the following array that has relational data (parent child relationships).

Array        
(        
    [5273] => Array        
        (        
            [id] => 5273        
            [name] => John Doe        
            [parent] =>         
        )        

    [6032] => Array        
        (        
            [id] => 6032        
            [name] => Sally Smith        
            [parent] => 5273        
        )        

    [6034] => Array        
        (        
            [id] => 6034        
            [name] => Mike Jones        
            [parent] => 6032        
        )        

    [6035] => Array        
        (        
            [id] => 6035        
            [name] => Jason Williams        
            [parent] => 6034        
        )        

    [6036] => Array        
        (        
            [id] => 6036        
            [name] => Sara Johnson        
            [parent] => 5273        
        )        

    [6037] => Array        
        (        
            [id] => 6037        
            [name] => Dave Wilson        
            [parent] => 5273        
        )        

    [6038] => Array        
        (        
            [id] => 6038        
            [name] => Amy Martin        
            [parent] => 6037        
        )        
)        

I need it to be in this JSON format:

{        
   "id":"5273",        
   "name":"John Doe",        
   "data":{        

   },        
   "children":[        
      {        
         "id":" Sally Smith",        
         "name":"6032",        
         "data":{        

         },        
         "children":[        
            {        
               "id":"6034",        
               "name":"Mike Jones",        
               "data":{        

               },        
               "children":[        
                  {        
                     "id":"6035",        
                     "name":"Jason Williams",        
                     "data":{        

                     },        
                     "children":[        
                        {        
                           "id":"node46",        
                           "name":"4.6",        
                           "data":{        

                           },        
                           "children":[        

                           ]        
                        }        
                     ]        
                  }        
               ]        
            },        
            {        
               "id":"6036",        
               "name":"Sara Johnson",        
               "data":{        

               },        
               "children":[        

               ]        
            },        
            {        
               "id":"6037",        
               "name":"Dave Wilson",        
               "data":{        

               },        
               "children":[        
                  {        
                     "id":"6038",        
                     "name":"Amy Martin",        
                     "data":{        

                     },        
                     "children":[        

                     ]        
                  }        
               ]        
            }        
         ]        
      }        
   ]        
}        

I know I need to create a multidimensional array and run it through json_encode(). I also believe this method used to do this needs to be recursive because the real world data could have an unknown number of levels.

I would be glad to show some of my approaches but they have not worked.

Can anyone help me?

I was asked to share my work. This is what I have tried but I have not gotten that close to I don’t know how helpful it is.

I made an array of just the relationships.

foreach($array as $k => $v){
    $relationships[$v['id']] = $v['parent'];
}

I think (based off another SO post) used this relational data to create a the new multidimensional array. If I got this to work I was going to work on adding in the correct “children” labels etc.

$childrenTable = array();
    $data = array();
    foreach ($relationships as $n => $p) {
      //parent was not seen before, put on root
      if (!array_key_exists($p, $childrenTable)) {
          $childrenTable[$p] = array();
          $data[$p] = &$childrenTable[$p];  
      }
      //child was not seen before
      if (!array_key_exists($n, $childrenTable)) {
          $childrenTable[$n] = array();
      }
      //root node has a parent after all, relocate
      if (array_key_exists($n, $data)) {
          unset($data[$n]);
      }
      $childrenTable[$p][$n] = &$childrenTable[$n];      
    }
    unset($childrenTable);

print_r($data);
  • 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-06T20:44:07+00:00Added an answer on June 6, 2026 at 8:44 pm
    <?php
    header('Content-Type: application/json; charset="utf-8"');
    
    /**
     * Helper function
     * 
     * @param array   $d   flat data, implementing a id/parent id (adjacency list) structure
     * @param mixed   $r   root id, node to return
     * @param string  $pk  parent id index
     * @param string  $k   id index
     * @param string  $c   children index
     * @return array
     */
    function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children') {
      $m = array();
      foreach ($d as $e) {
        isset($m[$e[$pk]]) ?: $m[$e[$pk]] = array();
        isset($m[$e[$k]]) ?: $m[$e[$k]] = array();
        $m[$e[$pk]][] = array_merge($e, array($c => &$m[$e[$k]]));
      }
    
      return $m[$r][0]; // remove [0] if there could be more than one root nodes
    }
    
    echo json_encode(makeRecursive(array(
      array('id' => 5273, 'parent' => 0,    'name' => 'John Doe'),  
      array('id' => 6032, 'parent' => 5273, 'name' => 'Sally Smith'),
      array('id' => 6034, 'parent' => 6032, 'name' => 'Mike Jones'),
      array('id' => 6035, 'parent' => 6034, 'name' => 'Jason Williams'),
      array('id' => 6036, 'parent' => 5273, 'name' => 'Sara Johnson'),
      array('id' => 6037, 'parent' => 5273, 'name' => 'Dave Wilson'),
      array('id' => 6038, 'parent' => 6037, 'name' => 'Amy Martin'),
    )));
    

    demo: https://3v4l.org/s2PNC

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Converting date From one format to another I have a date, for
Possible Duplicate: How can I convert a list<> to a multi-dimensional array? I want
Possible Duplicate: PHP/MYSQL using an array in WHERE clause I have an array with
Possible Duplicate: Porting a C array declaration to Delphi I'm converting a C code
Possible Duplicate: Converting string to MySQL timestamp format in php Given a date in
Possible Duplicate: PHP get all arguments as array? Within a javascript function arguments always
Possible Duplicate: Converting Seconds to HH:MM:SS I have an integer as a number of
Possible Duplicate: Converting ereg expressions to preg <?php $searchtag = "google"; $link = "http://images.google.com/images?hl=de&q=$searchtag&btnG=Bilder-Suche&gbv=1";
Possible Duplicate: Byte array in objective-c Am converting some Java code to Objective-C and
Possible Duplicate: Converting ereg expressions to preg I have this ereg() expression: ^[0-9]{8}\T{1}[0-9]{2}\:[0-9]{2}\:[0-9]{2}$ How

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.