I need add a jsonArray in my json, I'm use a php class (User.php) to model the json. like this:
class User {
public $id = "";
public $nombre = "";
}
And I use other class (ArrayUser.php) to add the array from the class user to the final json
class ArrayUser {
public $usuarios;
}
I use those classes in my code in this way:
$tempArray = array();
$ArrayUser = new ArrayUser();
foreach ($sth as $sth) {
$user = new User();
$user->id = $sth['id'];
$user->nombre = $sth['name'];
array_push($tempArray, $user);
}
$ax = json_encode($tempArray);
$ArrayUser->usuarios = $ax;
$axX = json_encode($ArrayUser, true);
The result is this:
{
"usuarios": "[{"id":"1","nombre":"Leandro Gado"},{"id":"2","nombre":"Aitor Tilla"}]"
}
But I don't want the array like String (is not a valid Json by the way), actually I need my Json like that:
{
"usuarios": [{
"id": "1",
"nombre": "Leandro Gado"
}, {
"id": "2",
"nombre": "Aitor Tilla"
}]
}
I appreciate your help. Regards.
json_encode()don't encode individual pieces (btw, the second argument ofjson_encode()is a number, nottrue). If the data structure you want to encode as JSON is an object then make its class implement theJsonSerializableinterface. This way you can control what object properties are encoded and how.