-1

I am implementing jqGrid with multiple search. But I have a trouble to get an array into single value. This is my code:

//I get this from url giving by jqGrid

$json_data = '{"groupOp":"OR","rules":[{"field":"first_name","op":"eq","data":"ale"},{"field":"last_name","op":"ne","data":"ger"},{"field":"first_name","op":"cn","data":"ros"}]}';

$myArray = json_decode($json_data);

$theArray = $myArray->rules;


foreach($theArray as $tArr) 
{
    //echoing field
    $thisWhere = $tArr->field. " ";

    //get operation 
    if($tArr->op == 'eq') {
        $thisWhere .= '= '; //equal
        $thisWhere .= '"'.$tArr->data.'" '.$myArray->groupOp.' ';
    } 
    else if ($tArr->op == 'ne') {
        $thisWhere .= '<> '; //not equal
        $thisWhere .= $tArr->data.' '.$myArray->groupOp.' ';
    }
    else if ($tArr->op == 'lt') {
        $thisWhere .= '< '; //less
        $thisWhere .= $tArr->data.' '.$myArray->groupOp.' ';
    }
    else if ($tArr->op == 'le') {
        $thisWhere .= '<= '; //less equal
        $thisWhere .= $tArr->data.' '.$myArray->groupOp.' ';
    }
    else if ($tArr->op == 'gt') {
        $thisWhere .= '> '; //greater than
        $thisWhere .= $tArr->data.' '.$myArray->groupOp.' ';
    }

    echo $thisWhere; //echo inside foreach
    //return ===> first_name = "ale" OR last_name <> "ger" OR first_name < 20 OR
}

//echo $thisWhere; //return ===> first_name < 20 OR

if echoing inside foreach, return; first_name = "ale" OR last_name <> "ger" OR first_name < 20 OR

if echoing outside foreach, return; first_name < 20 OR

All I want is echoing or get $thisWhere variable outside foreach loop. So, I can do next step.

4

2 回答 2

1

$thisWhere每次都在通过循环进行重置。它只会有上一次迭代的结果。您需要附加到它。(我建议也将其设置''在循环之前,以避免通知和某些类型的奇怪。)

我通常更喜欢将条件分组到一个数组中,虽然......像这样:

# by the way, there's not really a need for all the if/else junk.
# watch this.
$ops = array(
    'eq' => '=',  'lt' => '<',  'gt' => '>',
    'ne' => '<>', 'ge' => '>=', 'le' => '<=',
);

# stringify each condition
$conditions = array();
foreach ($theArray as $comp) {
    $conditions[] = "{$comp->field} {$ops[$comp->op]} {$comp->data}";
}

# now you can just glue them together at the end
$thisWhere = implode(" {$myArray->groupOp} ", $conditions);

除了更简单之外,它还确保您只使用 AND/OR 来分隔条件。如果您在循环中执行此操作,则必须跳过一些圈子以避免OR在最后出现额外的问题。

于 2013-06-17T04:45:23.190 回答
0

使用内爆($theArray);将数组转换为单个字符串的方法。希望这会奏效。

于 2013-06-17T04:36:09.087 回答