Skip to content

Instantly share code, notes, and snippets.

@sshine
Created December 15, 2011 15:00
Show Gist options
  • Save sshine/1481386 to your computer and use it in GitHub Desktop.
Save sshine/1481386 to your computer and use it in GitHub Desktop.
Tree traversal in PHP
<?php
$recursive_array = array(
0 => array(
'name' => 'pets',
'category' => array(
0 => array(
'name' => 'cats',
'category' => array(
0 => array(
'name' => 'big cats',
'category' => array(
0 => array(
'name' => 'fat cats'
),
1 => array(
'name' => 'ill cats'
)
)
),
1 => array(
'name' => 'small cats'
)
)
),
1 => array(
'name' => 'ponies'
)
)
)
)
$catgroups = array();
$cats = array();
function traverse_cats(&$sub_array, $parent) {
global $catgroups, $cats;
foreach ($sub_array as &$sub) {
if (isset($sub['category'])) {
$catgroups[$sub['name']] = $parent;
traverse_cats($sub['category'], $sub['name']);
}
$cats[$sub['name']] = $parent;
}
}
traverse_cats($recursive_array, 'root');
?>
@Deele
Copy link

Deele commented Dec 16, 2011

Thanks, this really helped! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment