我正在尝试使用递归函数将数组解析为逻辑结构,到目前为止,只是接近遇到.
这是我收到的:
[
"1921",
"AND",
"(",
"1923",
"OR",
"(",
"1925",
"AND",
"1924",
")",
")"
]
Run Code Online (Sandbox Code Playgroud)
这就是我必须获得的:
{
terms: ["1921", {
terms: ["1923", {
terms: ["1925", "1924"],
operator: "AND"
}],
operator: "OR"
}],
operator: "AND"
}
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏!
我将它作为一个状态机来处理它,它存储当前索引并逐项迭代遍历数组.
class StateMachine {
protected $index = 0;
protected $data;
public function __construct($data) {
$this->data = $data;
}
public function getTree() {
return $this->parse($this->data);
}
protected function parse() {
$result = ["terms" => []];
while ($this->index < count($this->data)) {
switch($this->data[$this->index]) {
case "(":
$this->index++;
$result["terms"][] = $this->parse();
break;
case ")":
$this->index++;
return $result;
break;
case "AND":
$result["operator"] = "AND";
$this->index++;
break;
case "OR":
$result["operator"] = "OR";
$this->index++;
break;
default:
$result["terms"][] = $this->data[$this->index];
$this->index++;
break;
}
}
return $result;
}
}
$array = [
"1921",
"AND",
"(",
"1923",
"OR",
"(",
"1925",
"AND",
"1924",
")",
")"
];
$machine = new StateMachine($array);
print json_encode($machine->getTree());
Run Code Online (Sandbox Code Playgroud)
而且你会得到你所需要的.
将其重写为递归函数需要使用全局变量,但原理类似.
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |