How can i make the JSON based array in PHP - php

I would like to know how can we make the JSON based array using json_encode() PHP ;
The format of the array should be look like this.
callback([{"ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false}])
When we need the this header("Content-type: application/json");
UPDATE
in above format you can see the format check the numeric values, json_encode not mention the double quotes the numeric values. I just want to configure the Mysql values on this format, like numeric value without double quotes, and string values with double quotes. We should have to configure mysql values on this format.
Thanks

edit: It appears you are trying to serve JSONP, not JSON. JSONP should be given the content type of application/javascript like this:
header("Content-type: application/javascript");
$json = json_encode(
array(
array(
"ProductID" => 1,
"ProductName" => "Chai",
"UnitPrice" => 18,
"UnitsInStock" => 39,
"Discontinued" => false
)
)
);
echo "callback({$json})";

Example:
$array = array(
'ProductID' => 1,
'ProductName' => 'Chai',
'UnitPrice' => 18,
'UnitsInStock' => 39,
'Discontinued' => false
);
header("Content-type: application/json");
echo json_encode($array);

http://us.php.net/manual/en/function.json-encode.php
the example on that page should tell you everything you need to know.

Related

Why is \r\n appearing when I JSON encode an array

I'm creating some arrays and turning them into JSON strings and I noticed something strange--some of the strings,
when I JSON encode them, are getting \r\n added onto the front and end of the of the strings.
The strings I'm encoding are pulled from HTML elements.
$arr = array(
'licStat' => $rows2[13]->nodeValue,
'expDate' => dateReplace($data[5]->nodeValue),
'dicAct' => $rows2[11]->nodeValue
);
echo json_encode($arr);
Expected output:
{"licStat":"Expired","expDate":"1999-12-20","dicAct":"Yes"}
Actual output:
{"licStat":"\r\n Expired\r\n ","expDate":"1999-12-20","dicAct":"\r\n Yes\r\n "}
It seems $rows2[13]->nodeValue and $rows2[11]->nodeValue have carry return and line feeds in them.
You can use trim() to get rid of them:
$arr = array(
'licStat' => trim($rows2[13]->nodeValue),
'expDate' => dateReplace($data[5]->nodeValue),
'dicAct' => trim($rows2[11]->nodeValue)
);
echo json_encode($arr);

json_encode( json_encode (array) )

I'm trying to create a PHP script to generate JSON data for a jqplot bubble chart. The jqplot sample code requires data in the format
var arr = [
[45, 92, 1067, {label:"Alfa Romeo", color:'skyblue'}],
etc.
];
My script is along the lines of
while ...
array_push(
$arrBubble,
array(
11,
123,
1236,
json_encode(
array('label' => $car, 'color' => 'skyblue')
)
);
}
echo json_encode($arrBubble);
The problem is that the result is
[ [11, 123, 1236, "{\"label\":"VW", \"color\":\"skyblue\"}"] ]
The double json_encode has encoded the object(?) as a literal string.
What's the best way to work around this?
There is no reason to explicitly have a json_encode for one of the values inside the array. When you're using json_encode, it'll convert each level of the array as you expect.
var_dump(json_encode([
11,
123,
1236,
['label' => $car, 'color' => 'skyblue']
]));
Outputs the structure you want:
string(48) "[11,123,1236,{"label":"VW","color":"skyblue"}]"

Parse string to array like CakePHP form data

I am looking for a way to parse strings in an array to an array which has a similar pattern to how CakePHP handles POST data. Or even a function in CakePHP that would do it.
UPDATED:
Current array:
array(
'data[callers]' => (int) 4,
'data[status]' => 'Unknown',
'data[country_id][107]' => (int) 1,
'data[country_id][150]' => (int) 0
)
Desired result:
array(
'callers' => (int) 4,
'status' => 'Unknown',
'country_id' => array(
(int) 107 => (int) 1,
(int) 150 => (int) 0
)
)
The purpose is saving serialized form data which can later be passed to a PHP function without having to POST the data from the browser.
The data comes from a form which was serialized and saved in the database. CakePHP generates input names in the form with brackets like this: data[country_id][107] and inside the controller you can access it like this $this->request->data['country_id']['107']
But when I serialize the form with javascript and save the raw JSON string in the database I need a way to make it into an array like CakePHP does.
Firstly make sure your array is valid first like:
$data = array (
'callers' => 4,
'status' => 'Unknown',
'country_id' => array(
'107' => 0,
'150' => 0
)
);
JSON ENCODE
Now you can json encode it
$json = json_encode($data);
echo $json; // prints: {"callers":4,"status":"Unknown","country_id":{"107":0,"150":0}}
See ^ it is now a string.
http://php.net/manual/en/function.json-encode.php
JSON DECODE
Then when you need it as an array call json_decode()
json_decode($data, true);
Note the second parameter is setting return array to true else you will get an the json returned as an object.
http://php.net/manual/en/function.json-decode.php

Convert PHP Array to String?

I'm working with this PHP Array and I'm trying to convert it into a string:
$args=shortcode_atts( array(
'setting' => 'value',
'setting' => 'value',
'setting' => 'value',
), $atts);
The result should look like this:
' "setting":"value","setting":"value" '
I'm not sure how to loop through this? I've also noticed a lot of docs online that include the comma at the end of the last array item - is this ok or should I be in the habit of not including the comma?
I believe that you are looking for json encoded data:
$json = json_encode($args);

How to use json and php

I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!
Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.
Use json_encode() for encoding the array, get the array back by using json_decode().

Categories