Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build SQL statement from json encoded string php

Tags:

json

php

jqgrid

I'm trying to decode json encoded string into SQL statement withing php.

Lets say I've such a json encoded string =>

$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';

I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.

I've done this =>

$d = json_decode($j);

$filterArray = get_object_vars($d); // makes array


foreach($filterArray as $m_arr_name => $m_arr_key){
    // here I can't made up my mind how to continue build SQL statement which I've mentioned above 
}

Any idea how to do that?

like image 677
nanobash Avatar asked Aug 08 '26 01:08

nanobash


1 Answers

The first problem is you will want to pull out the groupOp operator.

Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.

Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.

You may want to look at this question to see how you can get data out of the array:

json decode in php

And here is another question that may be helpful for you:

How to decode a JSON String with several objects in PHP?

like image 126
James Black Avatar answered Aug 09 '26 17:08

James Black



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!