将PHP数组编写为单值

时间:2013-06-17 04:32:55

标签: php arrays

我正在通过多次搜索实施jqGrid。但我很难将数组转换为单值。这是我的代码:

//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

如果在foreach内回显,则返回; first_name = "ale" OR last_name <> "ger" OR first_name < 20 OR

如果在foreach之外回显,则返回; first_name < 20 OR

我想要的只是在$thisWhere循环之外回显或获取foreach变量。所以,我可以做下一步。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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