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.
Related
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]);
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.
When using json_encode, it annoyingly automatically coverts the int keys to strings. For example, if you have an array:
$a = array();
$a[12] = 15;
echo json_encode($a);
{"12":15} //notice the quotes around 12
After searching SO, the solution is to use
json_encode($array,JSON_NUMERIC_CHECK)
However, that is only available in php > 5.3.3. The production server I'm stuck with is using 5.3.2.
Surely there is a work around?
So the problem here is that you are basically mixing your approach to the data structure and json_encode() is trying to make a best guess as to how to interpret your array, since in JSON, there is not such concept of a non-zero based, numerically indexed array.
If for example, you had a zero-based numeric array with a continuous number sequence, json_encode() would encode this a a numerically-indexed array of the format:
[value1, value2, ...]
Since you don't have a zero-based array, your data structure is being interpreted as an object structure and given a string key (the only available key type for an object in JSON) of the format:
{"key", value}
So it seems you need to make up your mind as to what you are really trying to represent in your array. Do you only need a numerically based array, or do you need object encoding.
I my php file, I need to make my own Json array.
for($i=1;$i<$arraySize+1;$i++){
$idJson[$i]=$i.":".$birdIDArray[$i-1];
}
for($i=$arraySize+1 ;$i<$arraySize*2+1; $i++){
$idJson[$i]=$i.":".$rankArray[$i-($arraySize+1)];
}
When I use
print(json_encode($idJson));
the OUTPUT : ["0:3","1:15","2:3","3:14","4:1","5:2","6:2"]
But i need the output like this ["0":"3","1":"15","2":"3","3":"14","4":"1","5":2","6":"2"]
When I going to add " mark
for($i=1;$i<$arraySize+1;$i++){
$idJson[$i]=$i.'"'.":".'"'.$birdIDArray[$i-1];
}
for($i=$arraySize+1 ;$i<$arraySize*2+1; $i++){
$idJson[$i]=$i.'"'.":".'"'.$rankArray[$i-($arraySize+1)];
}
It prints like this
["0:3","1\":\"15","2\":\"3","3\":\"14","4\":\"1","5\":\"2","6\":\"2"]
How can I avoid from printing this \ sign?
I'm assuming you want a JSON object like this:
{"0":"3", ... }
The problem here is that Javascript/JSON distinguishes between key-value pairs, which are objects, and numerically indexed lists, which are arrays, while PHP uses arrays for both these things. With json_encode it depends on whether the PHP array is a continuously numerically indexed array, in which case you get a JSON array, or anything else, in which case you get a JSON object.
What you want is to force a JSON object even for a continuously numerically indexed array. The first question here would be: why?! But if you're really sure you want that (again, why?!), there's the JSON_FORCE_OBJECT flag in PHP 5.3+:
echo json_encode(array("3", "15", "3"), JSON_FORCE_OBJECT);
// {"0":"3","1":"15","2":"3"}
But I'll say again that that's pretty pointless. If you use a regular array like ["3","15","3"], the keys to those elements are already implicitly 0, 1 and 2. There's no need to enforce them as object keys.
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