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

我正在尝试将数组转换为类似条件的表达式字符串,该字符串将在JS Filtrex库中使用。JS 部分与此问题无关。


以下是我正在尝试使用的示例 PHP 数组。


$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'

        )

    )

);

结果字符串将是这样的:


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

我不卖数组结构,所以你可以自由修改数组,只要它可以用更多条件扩展。


提前致谢。


函数式编程
浏览 150回答 2
2回答

慕标琳琳

我不知道它是否适用于所有情况,但在您的情况下效果很好(我猜)我建议你删除嵌套数组$condition[1]并直接写入$condition[1][0]数组(新的数组结构在下面的代码中)<?php$condition = array(&nbsp; &nbsp; 'and',&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'field' => 'show_image',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'compare' => '==',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'value' => 1&nbsp; &nbsp; ),&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'or',&nbsp; &nbsp; &nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'field' => 'filter',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'compare' => '!=',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'value' => 1&nbsp; &nbsp; &nbsp; &nbsp; ),&nbsp; &nbsp; &nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'field' => 'align',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'compare' => '==',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'value' => 'left'&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; ));function generateExpression( Array $condition ) : String{&nbsp;return $condition['field'] . " " . $condition['compare'] . " " . $condition['value'];}function generateConditionExpression ( Array $conditionTree ) : String{&nbsp; if ( array_key_exists("field",$conditionTree)&nbsp; )&nbsp;&nbsp; {&nbsp; &nbsp; &nbsp;return generateExpression($conditionTree);&nbsp; }&nbsp; //else&nbsp; return "(" . generateConditionExpression( $conditionTree[1] ) . " " . $conditionTree[0] . " " . generateConditionExpression( $conditionTree[2] ) . ")";}echo generateConditionExpression($condition);
打开App,查看更多内容
随时随地看视频慕课网APP