求开发PHP脚本:将指定逻辑运算符表达式转为目标PHP数组
Solution
To convert your logical operator expression into a valid PHP array structure, we can build a recursive parser that handles nested parentheses and operator precedence (as dictated by parentheses). Note that the structure you provided has duplicate keys (OR appearing twice under the top-level AND), which is invalid in PHP—our solution will produce a valid structure where each group is an associative array nested within a numerically indexed array under the parent operator.
Here's the complete PHP script:
function parseLogicalExpression($expression) { // Clean up the input: remove curly braces, normalize whitespace $cleaned = preg_replace('/[\{\}]/', '', $expression); $cleaned = preg_replace('/\s+/', ' ', trim($cleaned)); // Helper function to split a string by an operator, ignoring instances inside parentheses $splitByOperator = function($str, $operator) use (&$splitByOperator) { $parts = []; $current = ''; $depth = 0; $opLength = strlen($operator); $strLength = strlen($str); for ($i = 0; $i < $strLength; $i++) { $char = $str[$i]; if ($char === '(') { $depth++; } elseif ($char === ')') { $depth--; } elseif ($depth === 0 && substr($str, $i, $opLength) === $operator) { // Found the operator at top level, split here $parts[] = trim($current); $current = ''; $i += $opLength - 1; // Skip the rest of the operator characters continue; } $current .= $char; } // Add the final part $parts[] = trim($current); return $parts; }; // Recursive function to parse a segment of the expression $parseSegment = function($str) use (&$parseSegment, $splitByOperator) { // Remove outer parentheses if present and parse the inner content if (str_starts_with($str, '(') && str_ends_with($str, ')')) { return $parseSegment(substr($str, 1, -1)); } // Check for top-level OR operators first $orSegments = $splitByOperator($str, 'OR'); if (count($orSegments) > 1) { $result = []; foreach ($orSegments as $segment) { $parsed = $parseSegment($segment); $result[] = is_array($parsed) ? $parsed : (int)$segment; } return ['OR' => $result]; } // Check for top-level AND operators $andSegments = $splitByOperator($str, 'AND'); if (count($andSegments) > 1) { $result = []; foreach ($andSegments as $segment) { $parsed = $parseSegment($segment); $result[] = is_array($parsed) ? $parsed : (int)$segment; } return ['AND' => $result]; } // If no operators, it's a single numeric value return (int)$str; }; return $parseSegment($cleaned); } // Usage example $inputExpression = "({2606} OR {2549} OR {2543} OR ({2605} AND {2562})) AND ({2387} OR {2383} OR {1990} OR {2412} OR {2411} OR {2409} OR ({2408} AND {2593}))"; $outputArray = parseLogicalExpression($inputExpression); // Print the result print_r($outputArray);
How It Works
- Input Cleaning: First, we remove curly braces and normalize whitespace to simplify parsing.
- Operator Splitting: The
splitByOperatorfunction splits the expression by a given operator (AND/OR) while ignoring instances inside parentheses by tracking the parenthesis depth. - Recursive Parsing: The
parseSegmentfunction recursively processes each segment:- Removes outer parentheses and parses the inner content.
- Checks for top-level
ORoperators first, building anORgroup array. - If no
ORoperators are found at the top level, checks forANDoperators and builds anANDgroup array. - If no operators are present, converts the segment to an integer.
Output Structure
The resulting array will be a valid PHP structure equivalent to your desired output (with duplicate keys fixed):
[ "AND" => [ ["OR" => [2606, 2549, 2543, ["AND" => [2605, 2562]]]], ["OR" => [2387, 2383, 1990, 2412, 2411, 2409, ["AND" => [2408, 2593]]]] ] ]
内容的提问来源于stack exchange,提问作者Muhammad Umair
相关产品推荐
相关产品推荐

