dongxiegao3071 2015-04-03 13:41
浏览 79

不知道为什么我的树构建函数返回一个空数组?

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.

  • 写回答

2条回答 默认 最新

  • dongyuandou2521 2015-04-03 14:34
    关注

    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)
    );
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大