Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >PHP RecursiveIterator遍历

PHP RecursiveIterator遍历
EN

Stack Overflow用户
提问于 2010-11-12 12:30:57
回答 2查看 4K关注 0票数 8

我有一个表示表单的结构,我想使用RecursiveIterator对其进行迭代。问题是这只返回顶级问题。我做错了什么?

整个表单:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Form implements RecursiveIterator{
    private $id;
    private $caption;
    private $other_text;
    private $questions = array();
    private $current;

    private function __construct(DibiRow $row){
        $this->id = $row->id;
        $this->caption = $row->caption;
        $this->other_text = $row->other_text;
        $this->loadQuestions();
    }

    private function loadQuestions(){
        $questions = dibi::query('SELECT * FROM cyp_questions WHERE form_id = %i AND parent_id IS NULL', $this->id);
        while($question = $questions->fetch()) $this->questions[] = new Question($question->question_id, $question->type, $question->caption, $question->other_text, $question->triggers_unique == 1);
    }

    /**
     * @throws InvalidArgumentException
     * @param $id
     * @return Form
     */
    public static function loadById($id){
        $form = dibi::query('SELECT * FROM cyp_forms WHERE id = %i', $id)->fetch();
        if($form === false) throw new InvalidArgumentException('Form with id '.$id.' was not found.');

        return new Form($form);
    }

    /**
     * @throws FormFieldException
     * @return bool
     */
    public function validate($postfields){

    }

    public function getQuestions(){
        return $this->questions;
    }

    public function getChildren(){
        return $this->questions[$this->current];
    }

    public function hasChildren(){
        return count($this->questions) > 0;
    }

    public function current(){
        return $this->questions[$this->current];
    }

    public function key(){
        return $this->current;
    }

    public function next(){
        $this->current++;
    }

    public function rewind(){
        $this->current = 0;
    }

    public function valid(){
        return isset($this->questions[$this->current]);
    }
}

问题:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Question implements RecursiveIterator{
    private $id;
    private $type;
    private $answers = array();
    private $subquestions = array();
    private $other_text;
    private $triggers_unique;
    private $caption;
    private $current = 0;


    public function __construct($id, $type, $caption, $other_text = null, $triggers_unique = false){
        $this->id = $id;
        $this->type = $type;
        $this->caption = $caption;
        $this->other_text = $other_text;
        $this->triggers_unique = $triggers_unique;  
        $this->setSubQuestions();   

    }

    private function setSubQuestions(){
        $questions = dibi::query('SELECT * FROM cyp_questions WHERE parent_id = %i', $this->id);
        while($question = $questions->fetch()) $this->subquestions[] = new Question($question->question_id, $question->type, $question->caption, $question->other_text, $question->triggers_unique == 1);
    }

    public function getOtherText(){
        return $this->other_text;
    }

    public function getCaption(){
        return $this->caption;
    }

    public function addAnswer($answer){
        $this->answers[] = $answer;
    }

    public function getChildren(){
        return $this->subquestions[$this->current];
    }

    public function hasChildren(){
        return count($this->subquestions) > 0;
    }

    public function current(){
        return $this->subquestions[$this->current];
    }

    public function key(){
        return $this->id;
    }

    public function next(){
        ++$this->current;
    }

    public function rewind(){
        $this->current = 0; 
    }

    public function valid(){
        return isset($this->subquestions[$this->current]);
    }

    public function getAnswers(){
        return $this->answers;
    }


}

迭代:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
$form = Form::loadById(1);

foreach($form as $question){
    echo $question->getCaption().'<br />';  
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-12 13:24:51

要遍历RecursiveIterator,必须将其包装到RecursiveIteratorIterator中。

查看下面的示例

默认的迭代模式是仅列出树叶。如果还希望包含节点出现在迭代中,请将RecursiveIteratorIterator::SELF_FIRST作为第二个参数传递给RecursiveIteratorIterator的构造函数

票数 9
EN

Stack Overflow用户

发布于 2010-11-12 12:56:38

如你所见,here

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public RecursiveIterator RecursiveIterator::getChildren ( void )

Returns an iterator for the current iterator entry. 

该方法应该返回一个实现迭代器的对象。您的方法返回一个简单的数组。

我的猜测是返回类似如下的内容:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public function getChildren(){
    return new Question($this->subquestions);
}

这是因为您使用的是递归迭代器,因此它应该具有相同类型的树的每个节点(迭代器)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4164623

复制
相关文章
如何从Serilog请求日志记录中排除健康检查终结点
这是在ASP.NET Core 3.X中使用Serilog.AspNetCore系列文章的第四篇文章:。
依乐祝
2020/02/17
1.4K0
在.Net Core中记录日志
一个完善的系统,必然会有非常完善的日志记录,用户的操作、系统的运行状况等信息被完整的记录下来,方便我们对系统进行维护和改进。.net core 也为日志记录提供了内置的支持。
拓荒者IT
2019/09/23
1.3K0
yii2自定义日志
1.新增公共配置文件(common/config/main-local.php) 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targ
botkenni
2022/01/10
2780
记录日志
日志级别:debug<info<warn<error application.yml配置日志 logging: file: target/app.log level: ROOT: WARN cn.devmar: TRACE import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SampleClass{ private static
华创信息技术
2019/11/08
7730
日志记录
访问应用服务器的请求都需要拥有一定权限,如果说每访问一个服务都需要验证一次权限,这个对效率是很大的影响。可以把权限认证放到 API 网关来进行。目前比较常见的做法是,用户通过登录服务获取 Token,把它存放到客户端,在每次请求的时候把这个 Token 放入请求头,一起发送给服务器。API 网关要做的事情就是解析这个 Token,知道访问者是谁(鉴定),他能做什么/访问什么(权限)。说白了就是看访问者能够访问哪些 URL,这里根据权限/角色定义一个访问列表。如果要实现多个系统的 OSS(Single Sign On 单点登录),API 网关需要和 CAS(Central Authentication Service 中心鉴权服务)做连接,来确定请求者的身份和权限。
用户1880875
2021/09/07
1.2K0
Django 中如何优雅的记录日志
日志是个好东西,但却并不是所有人都愿意记,直到出了问题才追悔莫及,长叹一声,当初要是记日志就好了。
AlwaysBeta
2020/11/11
1.9K0
Logback排除指定包/类/方法日志输出
Logback排除指定包或者类或者方法的日志输出 在logback-spring.xml中添加如下代码,可以一直点下去 <!--包--> <logger name="com.newbie.dao" level="OFF"></logger> <!--类--> <logger name="com.newbie.dao.NbDdiMonitorDao" level="OFF"></logger> <!--方法--> <logger name="com.newbie.dao.NbDdiMonitorDao.upd
4xx.me
2022/06/10
4.6K0
将Error异常日志从普通日志中剥离
  开发过程中经常需要调试和线上环境查看异常日志的需求,但普通消息与异常消息混在一起实在是非常难得找,上则NM的文档够你头痛,所以就将Error级别的日志抽离出来。   本示例采用log4net来配置:   1、先配置web.config,添加: <configSections> <!-- 添加log4net配置节 --> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4n
欢醉
2018/01/22
7500
将Error异常日志从普通日志中剥离
AWK中的字段,记录和变量【Programming】
本文为awk入门系列的第二篇文章,在本篇文章中,你可以了解到有关字段,记录和一些功能强大的awk变量。
Potato
2019/11/09
2.1K0
AWK中的字段,记录和变量【Programming】
Python 中更优雅的日志记录方案
在 Python 中,一般情况下我们可能直接用自带的 logging 模块来记录日志,包括我之前的时候也是一样。在使用时我们需要配置一些 Handler、Formatter 来进行一些处理,比如把日志输出到不同的位置,或者设置一个不同的输出格式,或者设置日志分块和备份。但其实个人感觉 logging 用起来其实并不是那么好用,其实主要还是配置较为繁琐。
崔庆才
2019/10/15
2K0
Python 中更优雅的日志记录方案
MongoDB日志记录
为了在发生故障时提供持久性,MongoDB使用预写日志记录到磁盘journal文件中。
MongoDB中文社区
2020/11/11
2.8K0
MongoDB日志记录
mysql日志记录
log-bin = /path/mysql-bin #其记录日志文件名为mysql-bin.index,mysql-bin.000001(注:重启或者单个文件超出限制会+1)
93年的老男孩
2019/12/18
4.7K0
查询listener的日志排除不能登录的错误
显然是Oracle的服务名设置错误,orcl的服务名是Oracle数据库最常用的服务名,难道会错?仔细看看listener的状态:
姚远OracleACE
2023/04/06
6270
查询listener的日志排除不能登录的错误
python 日志记录
#!/bin/env python #--*-- coding=utf8 --*-- # # Author: ablozhou # E-mail: ablozhou@gmail.com # # Copyright 2010 ablozhou # # Distributed under the terms of the GPL (GNU Public License) # # hzdq is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # 2010.3.14 写文件,log级别常数定义 import datetime import sys import traceback import codecs import types #log编码全部按utf8处理 loglevels = {'stdout':['info','debug','warn','error','fatal'], 'file':['info','debug','warn','error','fatal'] } logfile = 'logs.txt' class log4py: def __init__(self,modulename='gloabal', loglevel=loglevels, filename='log4py.txt'): self.filename = filename #self.flag = set(loglevel['stdout']+loglevel['file']) self.loglevel = loglevel self.modulename = modulename self.fcname = None class function(): def __init__(self,fcname,parent): parent.debug('enter ',fcname) self.fcname = fcname self.parent = parent def __del__(self): self.parent.debug('exit ',self.fcname) def dbgfc(self,fcname): '''set debug function name''' f = None if 'debug' in self.flag: f = self.function(fcname,self) return f def _gettime(self): return datetime.datetime.now().isoformat() def outstd(self,*fmt): s = self.fmtstr(*fmt) print s def outfile
py3study
2020/01/03
9030
[CodeIgniter4]-记录日志信息
你可以通过 log_message() 方法将信息记录在本地日志文件中,并且必须在第一个参数中指定错误的”级别”,来表明这个信息的类型(debug,error等)。 第二个参数就是信息本身:
landv
2020/03/05
1.3K0
yii2中LinkPager增加总页数和总记录数的实例
本文介绍了php中LinkPager增加总页数和总记录数,分享给大家,也给自己留个笔记
用户2323866
2021/07/02
8970
如何在Python中实现高效的日志记录
日志记录是软件开发中的重要组成部分,它可以帮助我们监控程序运行状态、诊断问题和优化性能。本文将详细介绍如何在Python中实现高效的日志记录,并提供详细的代码示例。
华科云商小彭
2023/08/29
4180
如何在Python中实现高效的日志记录
如何在Python 中更优雅的记录日志?
在 Python 中,一般情况下我们可能直接用自带的 logging 模块来记录日志,包括我之前的时候也是一样。在使用时我们需要配置一些 Handler、Formatter 来进行一些处理,比如把日志输出到不同的位置,或者设置一个不同的输出格式,或者设置日志分块和备份。但其实个人感觉 logging 用起来其实并不是那么好用,其实主要还是配置较为繁琐。
Python数据科学
2019/10/15
1.1K0
如何在Python 中更优雅的记录日志?
Apache日志变量详解
Apache日志格式字符串的含义 %% 百分号(Apache2.0.44或更高的版本) %a 远端IP地址 %A 本机IP地址 %B 除HTTP头以外传送的字节数 %b 以CLF格式显示的除HTTP头以外传送的字节数,也就是当没有字节传送时显示’-‘而不是0。 %{Foobar}C 在请求中传送给服务端的cookieFoobar的内容。 %D 服务器处理本请求所用时间,以微为单位。 %{FOOBAR}e 环境变量FOOBAR的值 %f 文件名 %h 远端主机 %H 请求使用的协议 %{Foobar}i 发送
院长技术
2020/08/24
4710
点击加载更多

相似问题

排除日志记录

21

从函数中排除日志记录

10

如何从POJO中排除某些变量以进行日志记录

112

yii2:如何从日志中排除DbTarget信息?

15

Yii2高级日志记录

11
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文