如何在php中将字符串和数组编码为json [duplicate]

This question already has an answer here:

I have some data from database which is like:

$name= "xxx";
$title= "xxx";
$arrayGender = array("Boy","Girl");
$arrayName = array("John", "Rosy");

How do I encode the data to a json object, so i guess the json would be something like:

{ 
  "name":"xxx",
  "title":"xxx",
  "children":[{"Boy","John"},{"Girl","Rosy"}]
}
</div>

You can create an object and set your target data in it. Then use json_encode() to converting php object into json.

$name= "xxx";
$title= "xxx";
$arrayGender = array("Boy","Girl");
$arrayName = array("John", "Rosy");

$obj = new stdClass;
$obj->name = $name;
$obj->title = $title;
$obj->children = [$arrayGender, $arrayName];

echo json_encode($obj);

Check the code in demo