编写PHP数组转换成单值 [英] Writing PHP Array Into Single Value
问题描述
我在执行的jqGrid
用多个搜索。但我有一个麻烦得到一个数组单一值。这是我的code:
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
如果在的foreach
呼应,回归; FIRST_NAME =ALEOR姓氏&LT;&GT; 蒙古包OR FIRST_NAME&LT; 20
如果外的foreach
呼应,回归; FIRST_NAME&LT; 20
if echoing outside foreach
, return; first_name < 20 OR
我要的是呼应或获得的foreach
循环外 $ thisWhere
变量。所以,我可以做下一步。
All I want is echoing or get $thisWhere
variable outside foreach
loop. So, I can do next step.
推荐答案
您正在重新 $ thisWhere
通过每次循环。这将只会有从上一次迭代的结果。你需要追加到它,而不是。 (我建议将其设置为前循环为好,以避免通知和某些类型带来不适。)
You're resetting $thisWhere
each time through the loop. It'll only ever have the results from the last iteration. You'd need to append to it instead. (I'd suggest setting it to ''
before the loop as well, to avoid notices and some types of oddness.)
我通常preFER到组的条件到一个数组,但...像这样:
I usually prefer to group the conditions into an array, though...like so:
# 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);
除了从简单了很多,这也确保你只使用和/或分离的条件。如果您在循环做它,你必须通过一些跳铁圈,以避免在年底额外或
。
这篇关于编写PHP数组转换成单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!