Skip to content

Instantly share code, notes, and snippets.

@vjandrea
Last active December 24, 2015 16:09
Show Gist options
  • Save vjandrea/6825675 to your computer and use it in GitHub Desktop.
Save vjandrea/6825675 to your computer and use it in GitHub Desktop.
Example in procedural code for a tree parser based on an array that i'd like to implement in ClosureTable It echoes the code that should be executed once implemented.
<?php
$data = [
[ 'id' => 0 ],
[ 'id' => 1 ],
[ 'id' => 2,
'children' => [
[ 'id' => 3 ],
[ 'id' => 4,
'children' => [
[ 'id' => 5 ],
],
],
],
],
];
function createFromArray($data = array(), $parent = null)
{
$last_id = $parent;
foreach($data as $key => $value)
{
if($key == 'id' && !is_array($value))
{
$last_id = $value;
if($parent != null)
{
// A parent is set, we can perform the moves
echo '$page = Page::find('.$value.')'."\n";
echo '$page->moveTo('.$parent.')'."\n";
}
}
elseif($key == 'children' && is_array($value) && !is_null($parent))
{
// A parent is set, we parse the subtree
createFromArray($value, $last_id);
}
elseif(is_array($value) && count($value))
{
// Key is not id nor children, we're at the root of the array
createFromArray($value, $last_id);
}
}
}
createFromArray($data);
@kapooostin
Copy link

I rarely use auto-incremented IDs, so my view is biased. But I guess at first we need the most common cases to be solved.

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