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 probably shouldn't have such a structure. That's what arrays are for.

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.

其他提示

You can convert a variable into using json_encode() (docs). Typically, this is used by passing an array:

$array = array($a, $b, $c);

$result = json_encode($array);

Edit (from the comments):

If you want to separate each value, you may (as you've mentioned in your comments) call the encode function on each string separately. For example, you may still put them into an array and use

$result = array_map('json_encode', $array);

$result will contain 3 json encoded strings, but the variable itself is still an array.

Of course, you may still use:

$a = json_encode($a);
$b = json_encode($b);
$c = json_encode($c);

Maybe this can help you: json_encode function

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top