I have a series of PHP variables:
$a = "a";
$b = "b";
$c = "c";
and so on...
How can I convert all these variables into one single JSON object? Is this possible?
I have a series of PHP variables:
$a = "a";
$b = "b";
$c = "c";
and so on...
How can I convert all these variables into one single JSON object? Is this possible?
You're currently storing data as sequential strings. This is a bad idea to begin with. When you have data that can be grouped together, it's almost always better to use an array instead. That makes things a whole lot easier.
Now to answer your original question:
If the number of variables are known, you could simply create an array first and then use json_encode()
to create the JSON string:
$arr = array($a, $b, $c);
$json = json_encode($arr);
If the variable names aren't known beforehand, you could use get_defined_vars()
to get a list of defined variables.
$arr = array_filter(get_defined_vars(), 'is_string');
echo json_encode($arr);
This is a bad idea though. This would only work if all the variables are to be included in the JSON representation. For example, if you had a private variable $somePrivateData
defined in your code, the JSON string will also contain the value of that variable.