我正在開發一個 Laravel/php 應用程式,我有這個陣列,我想在其中收集最終結果:
[
{
"nodeType": "or",
"0": {
"nodeType": "and",
"0": {
"nodeType": "and",
"1": true,
"2": false
},
"3": true
},
"2": {
"nodeType": "or",
"4": false,
"5": true
}
}
]
我希望能夠收集 True 或 False 的最終值。陣列本身可以包含任意數量的子元素,例如:
[
{
"nodeType": "or",
"0": {
"nodeType": "and",
"0": {
"nodeType": "or",
"0": {
"nodeType": "and",
"1": true,
"2": false
},
"3": true
},
"3": true
},
"2": {
"nodeType": "or",
"4": false,
"5": true
}
}
]
解決這個問題的最佳方法是什么?我認為回圈不起作用,因為陣列的深度不固定。
編輯1:回答評論中的一些問題。鍵不重要。節點總是有兩個值。但是一個值可以有它的兩個值,就像第二個例子一樣。外層是一個陣列,但這個陣列只有一個條目。所以它可以簡單地用于array[0]獲取 json 物件。
編輯 2:以下陣列的結果應該為 false,但第一個答案回傳 true。
{
"nodeType": "and",
"0": {
"nodeType": "and",
"0": {
"nodeType": "and",
"1": true,
"2": false
},
"3": true
},
"2": {
"nodeType": "or",
"4": false,
"5": true
}
}
nodetype可以是and或。or它并不總是如上面的示例中所寫。
uj5u.com熱心網友回復:
您可以使用遞回函式,如下所示:
function deduct($expr) {
if (is_bool($expr)) return $expr; // Base case
// If OR, we can stop when we find true (and return true).
// If AND, we can stop when we find false (and return false).
$search = $expr["nodeType"] == "or";
foreach ($expr as $key => $value) {
if ($key !== "nodeType" && deduct($value) === $search) return $search;
}
// If that never happened, return the opposite (false for OR, true for AND)
return !$search;
}
使用第二個 JSON 作為輸入的示例呼叫:
$json = '[{"nodeType": "or","0": {"nodeType": "and", "0": {"nodeType": "or", "0": {"nodeType": "and","1": true,"2": false},"3": true},"3": true},"2": {"nodeType": "or","4": false,"5": true}}]';
$obj = json_decode($json, true)[0]; // The outer level is an array: unwrap it.
var_dump(deduct($obj));
輸出:
bool(true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429733.html
下一篇:無法使用遞回解決所有情況的冪和
