dongxi1943 2019-06-30 13:38
浏览 66
已采纳

在PHP中将多维数组转换为条件表达式

I'm trying to convert an array to condition-like expression string that will be used in the JS Filtrex library. The JS part is irrelevant for this question.

Following is a sample PHP array that I'm trying to work with.

$condition = array(
    'and',
    array(
        array(
            'field' => 'show_image',
            'compare' => '==',
            'value' => 1
        ),
    ),
    array(
        'or',
        array(
            'field' => 'filter',
            'compare' => '!=',
            'value' => 1
        ),
        array(
            'field' => 'align',
            'compare' => '==',
            'value' => 'left'
        )
    )
);

The resulting string will be something like this :

show_image == 1 and ( filter != 1 or align == "left" )

I'm not sold on the array structure so you're free to modify the array as long as it can be extended with more conditions.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • dqf67993 2019-06-30 14:35
    关注

    You just need to recurse such a structure, and switch according to the first element:

    • If it's a string, then treat the remaining arguments as operands/expressions, joined by operator

    • For associative arrays, just concat field/compare/value into a string

    For example:

    function join_expr($opts) {
        if (isset($opts["compare"])) {    // optional ↓↓↓ caretaking of value type(!)
            return "($opts[field] $opts[compare] '$opts[value]')";
        }
        elseif (gettype($opts[0]) == "string") {
            $op = array_shift($opts);
            return join(
                " $op ",
                array_map("join_expr", $opts)   // recurse on operands/subexpressions
            );
        }
        elseif (count($opts) == 1) {   // somewhat redundant
            return "(" . join_expr($opts[0]) . ")";
        }
        else {
            trigger_error("wrong struct");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。
  • ¥20 如何在visual studio 2022中添加ImageMagick库
  • ¥50 如何实现uniapp编译的微信小程序做可回溯视频
  • ¥15 求Houdini使用行家,付费。价格面议。