【问题标题】:PHP count all nodes in a treePHP计算树中的所有节点
【发布时间】:2013-03-13 07:47:52
【问题描述】:

我需要创建一个 Node 类,它实际上是一个节点树,并且在同一个类中我需要创建一个函数来计算树中的所有节点,包括根元素。 我能够用两个类(节点类和树类)做一些事情。我需要在一个类(节点)类中完成所有操作。

类似:

class myclass
{
       //Array of nodes with childs 

        public function count();
}

【问题讨论】:

  • 你尝试了吗?我们很想看看。

标签: php class tree nodes


【解决方案1】:

有点像

public function count() {
  $childCount = 0;
  foreach($this->childs as $c) $childCount+=$c->count();
  return 1 + $childCount;
}

【讨论】:

  • 在这个例子中节点类的结构是怎样的?我的意思是整个班级!
【解决方案2】:

可以使用count()函数的mode参数。

public function count() {
    return count(array, COUNT_RECURSIVE);
}

有关计数功能的更多信息,请参阅http://php.net/manual/en/function.count.php

【讨论】:

    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多