我正在尝试使用递归函数将数组解析为逻辑结构,到目前为止,只有近距离接触。
这是我收到的:
[
"1921",
"AND",
"(",
"1923",
"OR",
"(",
"1925",
"AND",
"1924",
")",
")"
]
这是我必须得到的:
{
terms: ["1921", {
terms: ["1923", {
terms: ["1925", "1924"],
operator: "AND"
}],
operator: "OR"
}],
operator: "AND"
}
感谢任何帮助!
我将把它当作存储当前索引并逐项递归迭代数组的状态机。
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());
你会得到你所需要的。
将其重写为递归函数需要使用全局变量,但原理是相似的。