Display multiple records in json using php mysql query - php

I have written a script to query a mysql database and encode the data in json format.
I have added $encoded = json_encode($encodable[0]); which removes the other [ ] brackets but then only displays 1 record. Is there a way to still remove those brackets but display for example every record that I am querying?
Sorry not sure how to describe the problem in a better way!

Encode the result set of the query as JSON? Or encode data that is being sent to the database??
$encodeable[0] is the first element of the array, so its clear that that is what will be encoded. Depending on the format of your data, encodeable[0] would be [{"key":"value"},{"key":"value"},{"key":"value"}] by default as thats an indexed array with keys of 0,1,2...
If your goal is to just output the json as a JS object {}, instead of an array [] you can use json_encode($array, JSON_FORCE_OBJECT); which will encode indexed arrays as {"0":"value"} or {"0":{"0":"value"}} instead of just ["value"] or [["value"]]. If that's not what you're after, you may just need to loop through each encodeable element of your array and encode that way (use a for loop)
http://php.net/manual/en/function.json-encode.php

Related

Best way to json encode an array that has a json encoded value already? PHP

I have an array with multiple items in it one of which is an already encoded json string. I'm wanting to json encode the whole array but in doing so it re-json_encodes the json and adds slashes to it. The only way I've found to fix this is to json_decode the value and then encode the whole array. I feel like this is a waste of resources though and I feel like there has to be a better way. Is doing it that way the best possible way?
Here's a sample of the array I'm trying to json_encode.
$arr = array();
$arr["var1"] = '{"test":"test"}';
$arr["var2"] = 'foo';
$arr["var3"] = 'bar';
If I don't decode the var1 first and I just encode the whole array I get a result like so
{"var1":"{\"test\":\"test\"}","var2":"foo","var3":"bar"}
Notice the slashes in the json object.
json_encode() returns a string containing the json representation of a value.
In the example, a php string is passed as one element of the array '{"test":"test"}', thus json_encode() is encoding it appropriately into json format, with escaped quotes "{\"test\":\"test\"}".
If decoding nested json is a very resource heavy task, a workaround is to use a placeholder instead of the value, {"var1":"PLACEHOLDER","var2":"foo","var3":"bar"}, and then using str_replace() to replace it.
However, simply decoding it as you described is probably a cleaner solution, if its not resource heavy.

Not sure why I can't get the values of this array or decode the json

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]);

php json_encode() output changes based on the array indices

I was trying to get some values from MySQL database and when converting into JSON array using json_encode() I got a JSON object , after a while I found out that the indices was the root cause of the problem
here's the example I mentioned
<?php
$array = array(0=>"zero",2=>"two");
$another_array=array(0=>"zero",1=>"one");
print_r(json_encode($array)); // output: {"0":"zero","2":"two"}
print_r(json_encode($another_array)); //output: ["zero","one"]
?>
so what's the reason for that ?
Because array(0=>"zero",1=>"one") is the same as array("zero", "one") and the JSON encoder assumes the latter is a list (since that's how PHP does lists) and has no way to tell the former from the latter.
If you want to force json_encode to treat all arrays as objects, pass JSON_FORCE_OBJECT as the second argument:
json_encode(array(0=>"zero",1=>"one"), JSON_FORCE_OBJECT)
// {"0":"zero","1":"one"}
If you always want a json list instead, get rid of the keys (e.g. using array_values()) before encoding.

Manipulate/Edit a json encoded string value in a database row

I'm working with laravel 4 and the eloquent implementation.
I want to edit/manipulate a value in a database field which contains a json encoded string.
Example: I have a database row with the name "meta". The value of "meta" is a json encoded string.
The example json encoded string:
{"name":"steven","lastname":"builder"}
How can I manipulate the value of that json string?
For example "name" ?
I've found mutators but I dont know how to work with them.
http://laravel.com/docs/eloquent#accessors-and-mutators
This works like most ORM's in that you simply make the change like you would to a normal object's properties, and just save the changes. In this example:
You've already got who you want to update, so we'll just call that object $meta, and you've already manipulated your json, so we'll call it $manip_json, and we'll say the column name is just meta_col
$meta->meta_col = $manip_json;
$meta->save();

PHP multidimensional array to JSON

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.

Categories