Is there a way to encode variables as strings that can be evaluated as php code? In particular, I'm interested in associative arrays. (Scalar values and indexed arrays are encoded as valid php code by json_encode. I don't need to encode objects and resources).
$Array = ['1', 2, 'key' => 'value'];
php_encode($Array); // => "[0 => '1', 1 => 2, 'key' => 'value']" or similar
You can use var_export with the second parameter set to true:
function php_encode($val)
{
return var_export($val, true);
}
http://php.net/manual/en/function.var-export.php
Related
I just created a small program to check JSON and JSON_FORCE_OBJECT
$tree = [
0 => array
(
'id' => 1,
'parent' => '0',
'name' => 'b',
'surname' => 'myfolder/b'
),
1 => array
(
'id' => 2,
'parent' => 1,
'name' => 'ignore',
'surname' => 'myfolder/ignore2'
),
2 => array
(
'id' => 3,
'parent' => 1,
'name' => 'ignore2',
'surname' => 'myfolder/ignore4'
)
];
var_dump($tree);
$try = json_encode($tree);//To print with key. Also if we decode we get result as object
//echo $try;
echo '<br />';
$try2 = json_decode($try,JSON_FORCE_OBJECT);
var_dump($try2);
$try2 is exactly equal to $tree an associative array.
Whereas if I remove JSON_FORCE_OBJECT from this line
$try2 = json_decode($try,JSON_FORCE_OBJECT);
I get an array with child object. Though JSON_FORCE_OBJECT is supposed to be used with json_encode but using it with json_decode, I get a surprising result. I am unable to understand whats going on inside?? I thought when I encode it and decode it I should get same result. But I got the same result only when I used JSON_FORCE_OBJECT. Can anyone please help why this happens?
According to the manual: http://php.net/manual/en/function.json-decode.php
json_decode returns an array of objects if you want to convert them in assoc array you should specify the second param which is a boolean
JSON_FORCE_OBJECT is an int with value 16...
when this is passed as second param php cast/converts it to its bool equivalent which true.
To test the above stated behavior try:
var_dump((bool)1; (bool)2, (bool)16)
//output bool(true) bool(true) bool(true) .
var_dump((bool)0)
//outputs bool(false)
So it's nothing to do with JSON_FORCE_OBJECT...even
json_decode($try,true);
json_decode($try,2);
json_decode($try,3);
json_decode($try,4);
json_decode($try,'someVar');
....
//should return your expected result (assoc array)
Similarly if you pass 0 as second param PHP will cast it into bool (which is false) and returns you an object
json_decode($try,0);
json_decode($try,false);
json_decode($try,null)
json_decode($try)
...
//will return objects
The second parameter to json_decode is a boolean. It accepts true or false. It does not accept JSON_FORCE_OBJECT. You're trying to use the wrong constant for the wrong function.
json_decode's 4th parameter accepts a bitmask of constants, but currently it only supports JSON_BIGINT_AS_STRING.
If you want to return stdClass instances for JSON objects from json_decode, set its second parameter to false (the default). Setting it to any non-falsey value makes it return associative arrays instead of objects. Setting it to JSON_FORCE_OBJECT counts as "not-falsey".
It's all described in the manual: http://php.net/json_decode
I'm using PHP v5.6.
As i read that php json_encode function is automatically converting int to string. But not in my case. Json_encode is still return it to int not string.
Like example:
json_encode(['code' => 200, 'results' => [id=> 1]]);
my expected results is all become a string. but what i get is
{"code":200,"results":{"id": 1}}
Expected output:
{"code":"200","results":{"id": "1"}}
How can i change all the result become string without using "" for every value?.
NB: results array is based on query.
In the link posted by Thomas in comments, one user suggests that you do this:
$data = json_encode(array_map('strval', $data));
This might not be the most efficient in terms of performace though, since every entry on the array will pass through the strval function.
json_encode(['code' => 200, 'results' => [id=> strval(1)]]);
With strval() php will return
The string value of var.
To ensure that all numeric "leaf nodes" of a potentially multi-dimensional array are cast as strings, call array_walk_recursive() and make conditional changes to each value type. By checking if the value "is numeric", you prevent values like null and booleans from being cast as strings.
Code: (Demo)
$array = [
'code' => 200,
'results' => [
'id' => 1
],
'a' => [
[
'b' => [
4,
null,
false
]
]
]
];
array_walk_recursive(
$array,
function(&$v) {
if (is_numeric($v)) {
$v = strval($v);
}
}
);
echo json_encode($array);
Output:
{"code":"200","results":{"id":"1"},"a":[{"b":["4",null,false]}]}
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().
How can I pass one or more variables of type array to another page via $_GET?
I always passed variable values in the form ?a=1&b=2&c=3
What about passing a=[1,2,3] ?
Do I need to write a for loop and append all the values?
Thanks
You can use the [] syntax to pass arrays through _GET:
?a[]=1&a[]=2&a[]=3
PHP understands this syntax, so $_GET['a'] will be equal to array(1, 2, 3).
You can also specify keys:
?a[42]=1&a[foo]=2&a[bar]=3
Multidimentional arrays work too:
?a[42][b][c]=1&a[foo]=2
http_build_query() does this automatically:
http_build_query(array('a' => array(1, 2, 3))) // "a[]=1&a[]=2&a[]=3"
http_build_query(array(
'a' => array(
'foo' => 'bar',
'bar' => array(1, 2, 3),
)
)); // "a[foo]=bar&a[bar][]=1&a[bar][]=2&a[bar][]=3"
An alternative would be to pass json encoded arrays:
?a=[1,2,3]
And you can parse a with json_decode:
$a = json_decode($_GET['a']); // array(1, 2, 3)
And encode it again with json_encode:
json_encode(array(1, 2, 3)); // "[1,2,3]"
Dont ever use serialize() for this purpose. Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.
You can pass an associative array to http_build_query() and append the resulting string as the query string to the URL. The array will automatically be parsed by PHP so $_GET on the receiving page will contain an array.
Example
$query_str = http_build_query(array(
'a' => array(1, 2, 3)
));
$city_names = array(
'delhi',
'mumbai',
'kolkata',
'chennai'
);
$city_query = http_build_query(array('city' => $city_names));
this will give you:
city[0]=delhi&city[1]=mumbai&city[2]=kolkata&city[3]=chennai
if you want to encode the brackets also then use the below code:
$city_query = urlencode(http_build_query(array('city' => $city_names)));
Output:
city%255B0%255D%3Ddelhi%26city%255B1%255D%3Dmumbai .....
Reference: http_build_query, urlencode
Just repeat your $_GET variables like this: name=john&name=lea
This gives you an array.
I used to believe it would be overwritten!
This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 1 year ago.
I am using a plugin that requires an array of associative rows as a json formatted string -- something like:
[
{oV: 'myfirstvalue', oT: 'myfirsttext'},
{oV: 'mysecondvalue', oT: 'mysecondtext'}
]
How do I convert my multidimensional array to valid JSON output using PHP?
Once you have your PHP data, you can use the json_encode function; it's bundled with PHP since PHP 5.2.
In your case, your JSON string represents:
a list containing 2 elements
each one being an object, containing 2 properties/values
In PHP, this would create the structure you are representing:
$data = array(
(object)array(
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext',
),
(object)array(
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext',
),
);
var_dump($data);
The var_dump gets you:
array
0 =>
object(stdClass)[1]
public 'oV' => string 'myfirstvalue' (length=12)
public 'oT' => string 'myfirsttext' (length=11)
1 =>
object(stdClass)[2]
public 'oV' => string 'mysecondvalue' (length=13)
public 'oT' => string 'mysecondtext' (length=12)
And, encoding it to JSON:
$json = json_encode($data);
echo $json;
You get:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
By the way, from what I remember, I'd say your JSON string is not valid-JSON data: there should be double-quotes around the string, including the names of the objects' properties.
See http://www.json.org/ for the grammar.
The simplest way would probably be to start with an associative array of the pairs you want:
$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");
then use a foreach and some string concatenation:
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";
Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.
This is one of the most fundamental rules in php development:
DO NOT MANUALLY BUILD A JSON STRING.
USE json_decode().
If you need to populate your data in a loop, then gather all of your data first, then call json_encode() just once.
Do not try to wrap/prepend/append additional data to an encoded json string. If you want to add data to the json payload, then decode it, add the data, then re-encode it.
It makes no difference if you pass object type or array type data to json_encode() -- by default, it will still create a string using square braces for indexed arrays and curly braces for iterable data with non-indexed keys.
Code:
$array = [
[
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext'
],
[
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext'
]
];
echo json_encode($array);
Output:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
For clarity, I should express that the OP's desired output is not valid json because the nested keys are not double quote wrapped.
You can use the stdClass, add the properties and json_encode the object.
$object = new stdClass();
$object->first_property = 1;
$object->second_property = 2;
echo '<pre>';var_dump( json_encode($object) , $object );die;
VoilĂ !
string(40) "{"first_property":1,"second_property":2}"
object(stdClass)#43 (2) {
["first_property"]=>
int(1)
["second_property"]=>
int(2)
}
This is the php code to generate json format.
while ($row=mysqli_fetch_assoc($result))
{
$array[] = $row;
}
echo '{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead