I want to create a JSON tree from a flat structure - in this case an App.net Thread.
I want JSON like this
"id": "12345",
"name": "Ringo",
"data":
{
"avatar": "",
"text": "We All Live",
},
"children": [{
"id": "34567",
"name": "John",
"data":
{
"avatar": "",
"text": "In a pink submarine?",
},
"children": [{
"id": "35555",
"name": "George",
"data":
{
"avatar": "",
"text": "Don't be daft",
},
"children": []
}]
},{
"id": "98765",
"name": "Paul",
"data":
{
"avatar": "",
"text": "In a yellow submarine?",
},
"children": []
}]
So, each post can have multiple children. Each child can have children.
The JSON coming back from App.net is not threaded.
{
"id": "98765",
"parent": "12345"
"details": {
...}
},
{
"id": "34567",
"parent": "12345"
"details": {
...}
},
I've used json_decode() to get the JSON response in to an array. I can iterate through using foreach.
How do I put each post in the correct part of the multi dimensional array?
Parent
|_
|-child
|-child
| |-child
|-child
etc
I would use references, the oft forgotten hard link of PHP. Something like this:
I'm assuming you have a $posts array that you've gotten back from an App.net API call.
(untested, may not compile / run / may have errors / may be more efficient ways to do this)
// first throw everything into an associative array for easy access
$references = array();
foreach ($posts as $post) {
$id = $post['id'];
$post['children'] = array();
$references[$id] = $post;
}
// now create the tree
$tree = array();
foreach ($references as &$post) {
$id = $post['id'];
$parentId = $post['parent'];
// if it's a top level object, add it to the tree
if (!$parentId) {
$tree[] =& $references[$id];
}
// else add it to the parent
else {
$references[$parentId]['children'][] =& $post;
}
// avoid bad things by clearing the reference
unset($post);
}
// encode it
print json_encode($tree);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With