3

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?

Francesco - FL
  • 603
  • 1
  • 4
  • 25
nanobash
  • 5,419
  • 7
  • 38
  • 56

2 Answers2

1

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?

Community
  • 1
  • 1
James Black
  • 41,583
  • 10
  • 86
  • 166
0

There is an answer with an implementation for the server-side php code here

Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:

$filters = str_replace('\"','"' ,$_POST['filters']);
Community
  • 1
  • 1
Robert Imhoff
  • 471
  • 4
  • 6