Jump to content

[SOLVED] Recursion Question


ionik

Recommended Posts

This is something I have avoided for the longest time......and now I need a bit of help  ???

 

What I am trying to do is simply build a recursive array based on parent->child, the recursion comes when their is the possibility to add any number of sub-children to sub-children so on and so forth.

 

Array need to run

array(4) {
  [12] => array(3) {
    ["title"] => string(7) "My Blog"
    ["parentId"] => string(1) "0"
    ["url"] => string(7) "my-blog"
  }
  [13] => array(3) {
    ["title"] => string(9) "Job Stuff"
    ["parentId"] => string(2) "12"
    ["url"] => string(9) "job-stuff"
  }
  [14] => array(3) {
    ["title"] => string(14) "More Job Stuff"
    ["parentId"] => string(2) "13"
    ["url"] => string(0) ""
  }
  [15] => array(3) {
    ["title"] => string(13) "Another Child"
    ["parentId"] => string(2) "12"
    ["url"] => string(0) ""
  }
}

 

to become!

 

array(4) {
  [12] => array(3) {
    ["title"] => string(7) "My Blog"
    ["parentId"] => string(1) "0"
    ["url"] => string(7) "my-blog"
    ["children"] => array(int) {
       [13] => array(3) {
          ["title"] => string(9) "Job Stuff"
          ["parentId"] => string(2) "12"
          ["url"] => string(9) "job-stuff"
          ["children"] => array(int) {
                [14] => array(3) {
                   ["title"] => string(14) "More Job Stuff"
                   ["parentId"] => string(2) "13"
                   ["url"] => string(0) ""
               }
          }
        [15] => array(3) {
            ["title"] => string(13) "Another Child"
            ["parentId"] => string(2) "12"
            ["url"] => string(0) ""
          }
       }
    }
}

I have taken a stab at this for about half a day and come fairly close but.....it just results in failure.

 

Any help would be apprected thanks!

Link to comment
https://forums.phpfreaks.com/topic/147993-solved-recursion-question/
Share on other sites

try

<?php
$test = array(
  12 => array (
    "title" =>  "My Blog",
    "parentId" =>  "0",
    "url" => "my-blog"
  ),
  13 => array (
    "title" => "Job Stuff",
    "parentId" => "12",
    "url" => "job-stuff"
  ),
  14 => array (
    "title" => "More Job Stuff",
    "parentId" => "13",
    "url" => ""
  ),
  15 => array (
    "title" => "Another Child",
    "parentId" => "12",
    "url" => ""
  )
);
//rearange array
foreach ($test as $k => $v){
$a[$v['parentId']][$k] = $v;
}


function my_child($a, $id = 0){
$out = array();
foreach ($a[$id] as $k =>$v){
	if (isset($a[$k])) $v['children'] = my_child($a, $k);
	$out[$k] = $v;
}
return $out;
}
$x = my_child($a);
print_r($x);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.