I have a json array like this:
$json = '[["Nome","contains","av"],"and",[["IdAreoporto","=",1],"and",["!",["IdAreoporto","=",3]]]]';
which basically is an sql. I need to obtain this:
$json = '((Nome like "%av%") and ((IdAreoporto = 1) and (not(IdAreoporto = 3))))';
so basically:
- change parenthesis
- replace commas with spaces
- remove quotes except if array length=3 and array[1] = 'contains'
- add % to array[2] just if array[1] = 'contains'
I tried a recursive function but I cannot make it work. Please can anybody help? it's driving me crazy. I tried to solve point 3 like this:
function setFilter( $filtri ){
$json = json_decode($filtri, false);
if(is_array($json)){
$count_j = count($json);
if(($count_j==3) && (!is_array($json[0])) && (!is_array($json[1])) && (!is_array($json[2])) ){
if($json[1]=='contains'){
$json[2]='|'.$json[2].'|';
}
} else {
foreach ($json as $item) {
if(is_array($item)){
$item = setFilter( json_encode($item) );
};
}
}
};
$json2 = json_encode($json);
return $json2;
}
So the Idea was to put a | where I want to keep the quote, then remove all the quotes, then replace | with quote.
any help? thank you!
****EDIT - I answer my last comment ****
I solved my last problem in the comment like this, what do you think?
// If there are three elements, manipulate the string into the required format
if (count($json) == 3) {
if ($json[$i] == 'contains'){
$json[$i] = 'like'; // Change 'contains' to 'like'
$json[$i + 1] = '"%'.$json[$i + 1].'%"'; // Encapsulate the following token in percentage symbols and quotes
} else if ($json[$i] == 'notcontains'){
$json[$i] = 'not like'; // Change 'notcontains' to 'not like'
$json[$i + 1] = '"%'.$json[$i + 1].'%"'; // Encapsulate the following token in percentage symbols and quotes
} else if ($json[$i] == 'startswith'){
$json[$i] = 'like'; // Change 'startswith' to 'like'
$json[$i + 1] = '"'.$json[$i + 1].'%"'; // Encapsulate the following token in percentage symbols and quotes
} else if ($json[$i] == 'endswith'){
$json[$i] = 'like'; // Change 'endswith' to 'like'
$json[$i + 1] = '"%'.$json[$i + 1].'"'; // Encapsulate the following token in percentage symbols and quotes
} else {
// I need to find out datatype so that I can add quotes in case of string
if(!is_array($json[$i])){
$array = ["=", "<>", "<", ">", "<=", ">="];
if (stripos(json_encode($array), $json[$i]) !== false) {
if (gettype($json[$i]=='string')){
$json[$i + 1] = '"'.$json[$i + 1].'"'; // it's a string, add quotes
}
};
}
};