I'm taking a flat array and creating a tree from it using the following function, but it always returns an empty array ($branch = array()
) on this set of data.
public static function buildTree($activities, $parent = 0)
{
$branch = array();
foreach ($activities as $activity) {
if ($activity['in_reply_to'] == $parent) {
$children = self::buildTree($activities, $activity['activity_id']);
if ($children) {
$activity['children'] = $children;
}
$branch[] = $activity;
}
}
return $branch;
}
And here's the data set.
Array
(
[0] => Array
(
[activity_id] => 583069095760826322
[in_reply_to] => 583068167603269635
)
[1] => Array
(
[activity_id] => 583068167603269635
[in_reply_to] => 582781728499965991
)
)
in_reply_to
references the activity_id
.
So, you can see that 0
is actually a child of 1
.
We don't have the data for the parent of 1
, so that should just be ignored based on the function.
Anyway, this is always returning an empty array and I'm not sure why.
Your problem is not on the code but on your data, you don't have a root node with "in_reply_to" = 0
Try to execute your code with this data set:
$activities = array(
array("activity_id" => 583069095760826322, "in_reply_to" => 583068167603269635),
array("activity_id" => 583068167603269635, "in_reply_to" => 0)
);
Assuming your activity_id
-field is auto incrementing r otherwise ordered, then you can find the lowest id inside your activities-array with this function and use it as the root.
public static function findLowestActivityID($activities)
{
$id = null;
foreach ($activities as $activity) {
if ($id === null || $id > $activity['activity_id']) {
$id = $activity['activity_id'];
}
}
return $id;
}
Example-Call:
$rootID = YourClassName::findLowestActivityID($activities);
$result = YourClassName::buildTree($activities, $rootID);