I am trying to return multiple arrays in one JSON object and having some difficulty with the syntax. An Android app receives updates from multiple tables, that I wish to be returned in one response.
Currently, this is how I am encoding the various result sets:
$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));
The data is returned in this format:
[{"table1":[{...}]},{"table2":[{...}]},...]
In the Android code, I'd like to be able to parse it as a JSONObject, from which I can then retrieve each array by name instead of parsing it as a JSONArray and retrieving each sub array by position. The JSON response would look like this instead:
{{"table1":[{...}]},{"table2":[{...}]},...}
It seems all I need to do is wrap the results arrays in an object, instead of an array on the PHP side, but although I've managed to blindly cobble together enough PHP code to get this far, I can't seem to figure out that final step.
Your last example is not valid JSON, curly braces always mean object with keys; instead you're treating it as an array. If you want an object, then add keys to the array in PHP like so:
$json=json_encode(array('a' => $table1, 'b' => $table2, 'c' => $table3));
This would then yield
{"a":{"table1":[{...}]},"b":{"table2":[{...}]},...}
Which seems to be what you want.
#Anonymous answer did the trick. Just to clarify, I had to clean up what I was doing previously, so instead of this:
$table1['table1'] =$stmt_table1->fetchAll(PDO::FETCH_ASSOC);
$table2['table2'] =$stmt_table2->fetchAll(PDO::FETCH_ASSOC);
...
$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));
I now have this:
$table1_results =$stmt_table1->fetchAll(PDO::FETCH_ASSOC);
$table2_results =$stmt_table2->fetchAll(PDO::FETCH_ASSOC);
...
$json=json_encode(array('table1' => $table1_results , 'table2' => $table2_results,...);
Related
I'm currently developing an API using Laravel for my project, the concept:
Retrieve JSON data from MySQL.
Receive user input from the Front-end (string).
Convert both JSON and string input into an array with similar structure. The array structure here is basically ["ObjectA", "ObjectA_quantity", "ObjectB", "ObjectB_quantity", ...].
Basically, eliminate the quantity of every object of Database's Array, based on every object that User Input's Array got. For example, if the Database's Array got ["pizza", "1", "burger", "2"], and the User Input's Array got ["pizza", "1"], the output of the method is expected to be ["burger", "2"].
The method that I developed will give inconsistent and confusing output, like for some object, it works well, for other it doesn't eliminate anything and if the User Input's Array too big (> 1 object), it also doesn't eliminate anything. I really welcome different approach or anything else that will give the expected output as above. Thank you very much
Here's the source code of the method I've develop: (method's located on: else if ($transactionGetter->type == 'return'), Line 148 and so forth)
https://github.com/andre-nk23/packme-backend/blob/master/app/Http/Controllers/API/TransactionController.php
if it's a JSON you must decode the value before access
$transactionGetter=json_decode($transactionGetter);
I am making a call to an API which should return a JSON array. I receive this:
Array
(
[0] => {"msg_id":"0t5OxT1ZP9VcF45L2","_text":"I want to reserve","entities":{"intent":[{"confidence":1,"value":"make_reservation","type":"value"}]}}
)
I know it's JSON because a) the docs say that's what I should be getting and b) I ran isJson($response) and got true.
I have tried to use json_decodebut the code just dies when I do (it errs saying it's expecting a string and got an array which makes sense but if I do json_encode that would just further encode the json from what I can understand).
As I understand it, I just need a way to traverse this array and get the "value:" key inside entities: intent:. However I can't figure out how to get it or where I'm wrong.
I have tried doing:
$val = $jsonArray[0]['entitites']['intent'][0]['value'] but nothing comes out.
You are trying to decode a PHP array that has encoded values.
You should try json_decode($jsonArray[0]) instead, so that you decode the value of the first array key, as that is the actual json string.
The data you posted is a php array where the value of the first element of the array is a json string.
json_decode($response[0]);
Using PHP, I printed out an array ($result) using print_r. But the format in which the array has been returned is a new one on me. Specifically, how do I retrieve the text found in the field "reviews_review" ("Wow, what a great...") when it's found in this particular format with its multiple values? Example:
stdClass Object
(
[node_reviews_nid] => 5270
[reviews_review] => a:2:{s:5:"value";s:38:"Wow, what a great place. The bestest!";s:6:"format";s:13:"filtered_html";}
Those extra values and curly brackets have got me stumped. If I wanted the node_reviews_nid I could simply use $result->node_reviews_nid" - but doing that to get reviews_review just retrieves too much ie,
a:2:{s:5:"value";s:38:"Wow, what a great place. The bestest!";s:6:"format";s:13:"filtered_html";})
The odd curly brackets you're seeing are the result of PHP's serialize function.
Basically it's intended to convert complex structures like objects, nested arrays and so on into simple strings which are easier and safer to transfer, for example over HTTP. Think of it as JSON representation, but specific to PHP (do not attempt to json_decode() a serialized value).
Also worth noting is that serialize-d string has a maximum length, beyond which it's simply truncated, so avoid using it for very large structures - you'll lose data.
The reverse of that is unserialize. So to read the review's text, you would first have to unserialize the "reviews_review" property, then reference the "value" index of the resulting array.
$review_data = unserialize($result->reviews_review);
$review_text = $review_data['value'];
print($review_text);
The data in reviews_review looks like a serialized array i.e. written using the serialize() function
So you will need to unserialize it using unserialize() before you can use it
$review = unserialize($obj->reviews_review);
print_r($review);
So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.
Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.
I want to assign multiple values to the same key, for example:
[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]
I think that is not going to work right? Because i dont have any type of index's?
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
For every row fetched from MySQL
$arr[$key] = <new array>
for each package:
append package to $arr[$key]
echo out json_encode($arr)
JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:
var x = []; // create new empty array
x[0] = {"key1": .... }; // first object
x[1] = {"key2": ....} // second object
Note that the contents of your {} sub-objects is NOT valid.
You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.
essentially, JSON is a transmission format, not a manipulation format.
Welcome Stackoverflow nation ! 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 ideas how to do that , thanks preliminarily :)
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?
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']);