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条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败