I have following array
[
["client_code","contains","12"],
"and",
[
["trade_name","=","KeyWholesaler"],
"or",
["trade_name","=","Cash&Carry"]
],
"and",
[
"!",
["state","=","B-BigCantina"],
["state","=","B-BigCantina2"]
],
"and",
["client_name","contains","M"]
]
I have made a function that recursively echo
above array into MySql
where query. I know it is messy but It's best I could do to make it work.
function testing($array) {
if(is_array($array) && count($array) == count($array, COUNT_RECURSIVE)) {
$is_not = $_SESSION["NOT"];
$and = $_SESSION["NOT"] ? " AND" : "";
echo "`$array[0]` $is_not$array[1] '$array[2]' $and";
echo "";
} else if(is_array($array)) {
echo "(";
foreach ($array as $key => $value) {
testing($value);
}
echo ")";
$_SESSION["NOT"] = "";
} else if($array == "!") {
$_SESSION["NOT"] = "!";
} else {
echo $array;
echo "";
}
}
The output of following function using given array is as
(`client_code` contains '12' and(`trade_name` = 'KeyWholesaler' or`trade_name` = 'Cash&Carry' )and(`state` != 'B-BigCantina' AND`state` != 'B-BigCantina2' AND)and`client_code` contains '21' )
Now this function is just echoing following output but I want to get it into a variable.
Sorry for all formatting and bad english. :)
CodePudding user response:
You can return from within the function and append as string to make a function recursive
function testing($array) {
if(is_array($array) && count($array) == count($array, COUNT_RECURSIVE)) {
$is_not = $_SESSION["NOT"];
$and = $_SESSION["NOT"] ? " AND" : "";
return "`$array[0]` $is_not$array[1] '$array[2]' $and";
} else if(is_array($array)) {
$val = "";
foreach ($array as $key => $value) {
$val = $val . testing($value);
}
$_SESSION["NOT"] = "";
return "(".$val.")";
} else if($array == "!") {
$_SESSION["NOT"] = "!";
} else {
return $array;
}
}
echo testing([]);