开发者

create truth table in php (AND / OR)

i have an array contain value like

Array
(
    [0] = true
    [1] = OR
    [2] = true
    [3] = AND
    [4] = false
    [5] = AND
    [6] = true开发者_如何学C
)

i want to create truth table in php like e.g

true OR true = result1
result1 AND false = result2
result2 AND true = result3

i'm stupid and not b able to create yet. :(

here is my code

foreach( $arrValue as $val  )
{
     if(!empty($val))
     {
    if($val=='true')
        $p = true;
    elseif($val=='false')
        $p = false;

    if(isset($p))
    {
            if(isset($result))
        {
             if($val=='AND')
             $result = $result AND $p;                      
        elseif($val=='OR')
             $$result = $result or $p;              

        }
       else
        $result = $p;
    }           
    }
}

please help this stupid boy to get results.


have you thought about creating a truth table with callbacks, for example:

$table = array();

$table[] = array(
    'name' => 'equals',
    'call' => 'check_equals'
);

$table[] = array(
    'name' => 'or',
    'call' => 'check_or'
);

$myData = array(
    true => true,
    false => true,
    true => false,
    true => -1,
)


foreach($myData as $first => $second)
{
     foreach($table as $check)
     {
         echo $check['name'] . call_user_func($check['call'],$first,$second) ? 'good' : 'bad';
     }
}

adn then just create your callbacks like so:

function check_or($f1,$f2)
{
    return $f1 || $f2;
}

function check_equals($f1,$f2)
{
    return $f1 === $f2;
}


This is what i want.

//( [0] => true [1] => OR [2] => true [3] => AND [4] => false [5] => AND [6] => true)

function boolstr($val) {
    if($val=='true')
        return true;
    elseif($val=='false')
        return false;
}


function row_operator($arrValue){
    $i=-2; $j=-1;
    foreach( $arrValue as $val  )
    {
        if($i+3 > count($arrValue)) break;
        $boolste = boolstr($arrValue[$i+2]);
        if(isset($res))
        {
            if($arrValue[$j+2]=='AND')
                $res = $res && $boolste;
            elseif($arrValue[$j+2]=='OR')           
                $res = $res || $boolste;            

            if($res==true)
                $a='true';
            else $a= 'false';
                $j += 2;
        }
        else
            $res = $boolste;

        $i += 2;
    }
    return $res;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜