You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求开发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

  1. Input Cleaning: First, we remove curly braces and normalize whitespace to simplify parsing.
  2. Operator Splitting: The splitByOperator function splits the expression by a given operator (AND/OR) while ignoring instances inside parentheses by tracking the parenthesis depth.
  3. Recursive Parsing: The parseSegment function recursively processes each segment:
    • Removes outer parentheses and parses the inner content.
    • Checks for top-level OR operators first, building an OR group array.
    • If no OR operators are found at the top level, checks for AND operators and builds an AND group 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:30:37