fork download
  1. <?php
  2. $haystack = array(
  3. array("id" => 1,"parent" => 0,"route" => "home","children" => array()),
  4. array("id" => 2,"parent" => 0,"route" => "news","children" => array()),
  5. array("id" => 3,"parent" => 0,"route" => "photography","children" => array(
  6. array("id" => 6,"parent" => 3,"route" => "photography/portraits","children" => array()),
  7. array("id" => 7,"parent" => 3,"route" => "photography/countries","children" => array()),
  8. array("id" => 8,"parent" => 3,"route" => "photography/landscapes","children" => array(
  9. array("id" => 9,"parent" => 8,"route" => "photography/landscapes/city","children" => array()),
  10. array("id" => 10,"parent" => 8,"route" => "photography/landscapes/wilderness","children" => array())
  11. )
  12. )
  13. )
  14. ),
  15. array("id" => 4,"parent" => 0,"route" => "about","children" => array()),
  16. array("id" => 5,"parent" => 0,"route" => "contact","children" => array()),
  17. );
  18.  
  19. function recurse($needle = -1, $haystack = NULL){
  20. static $_tmp = array();
  21.  
  22. if (count($_tmp) == 0 && $haystack != NULL && count($haystack) > 0) {
  23. foreach($haystack as $key => $item) {
  24. if (count($_tmp) == 0) {
  25. echo $needle ." === ". $item["id"] . "<br/>\n";
  26.  
  27. if((string)$item["id"] === (string)$needle){
  28. echo "Found: " . $needle . "<br/>\n";
  29. $_tmp = $item;
  30. //break;
  31. return $_tmp;
  32. } elseif (!empty($item["children"])) {
  33. echo "calling ". $item["id"]. ".children <br/>\n";
  34. $_tmp = recurse($needle, $item["children"]);
  35. }
  36. }
  37. }
  38. }
  39. return $_tmp;
  40. }
  41.  
  42. $test = recurse(9, $haystack);
  43. print_r($test);
  44.  
  45. ?>
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
9 === 1<br/>
9 === 2<br/>
9 === 3<br/>
calling 3.children <br/>
9 === 6<br/>
9 === 7<br/>
9 === 8<br/>
calling 8.children <br/>
9 === 9<br/>
Found: 9<br/>
Array
(
    [id] => 9
    [parent] => 8
    [route] => photography/landscapes/city
    [children] => Array
        (
        )

)