我有一个这种格式的对象可以无限深。
stdClass Object
(
[condition] => AND
[rules] => Array
(
[0] => stdClass Object
(
[id] => app
[field] => app
[type] => string
[operator] => equal
[value] => files_sharing
)
[1] => stdClass Object
(
[id] => deviceType
[field] => deviceType
[type] => string
[input] => select
[operator] => equal
[value] => android
)
[2] => stdClass Object
(
[id] => userGroup
[field] => userGroup
[type] => string
[operator] => equal
[value] => admin
)
[3] => stdClass Object
(
[condition] => AND
[rules] => Array
(
[0] => stdClass Object
(
[id] => userGroup
[field] => userGroup
[type] => string
[operator] => equal
[value] => group
)
[1] => stdClass Object
(
[id] => time
[field] => time
[type] => time
[input] => text
[operator] => between
[value] => Array
(
[0] => 12:30 am -0500
[1] => 06:00 am -0500
)
)
[2] => stdClass Object
(
[id] => request
[field] => request
[type] => string
[input] => select
[operator] => equal
[value] => post
)
)
)
)
)
我试图进入的格式是
array(
0 => array(
'condition' => 'and',
'rules' => array({RULESHERE})
),
1 => array(
'condition' => 'and',
'rules' => array({RULES HERE})
),
);
我现在拥有的是这个,但它是失败的核心。
Public function loop(obj) {
// First we get the condition
$this->stack[$this->stackCounter]['condition'] = $obj->condition;
$this->stack[$this->stackCounter]['rules'] = array();
foreach ($obj as $rule) {
if (isset($rule->condition)) {
$this->loop($rule);
} else {
array_push($this->stack[$this->stackCounter]['rules'], $rule);
// $this->evalCondition($rule);
}
}
$this->stackCounter++;
}
}
有人可以帮助一个白痴。
答案 0 :(得分:2)
尝试
foreach ($obj->rules as $rule) {
堆栈计数器应作为参数传递,以使其成为本地。否则,只要进入分支循环,堆栈计数器就会全局更改,然后返回迭代下一个规则。所以代码看起来像这样:
public function loop($obj, $stackCounter)
{
$this->stack[$stackCounter]['condition'] = $obj->condition;
$this->stack[$stackCounter]['rules'] = array();
foreach ($obj->rules as $rule) {
if (isset($rule->condition)) {
$this->loop($rule, $stackCounter + 1);
} else {
array_push($this->stack[$stackCounter]['rules'], $rule);
}
}
}