1

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.

2
  • 4
    There is no thing like "json array". JSON is a text representation of some data structure. Build your data structure then pass it to json_encode() don't encode individual pieces (btw, the second argument of json_encode() is a number, not true). If the data structure you want to encode as JSON is an object then make its class implement the JsonSerializable interface. This way you can control what object properties are encoded and how. Commented Mar 9, 2017 at 21:41
  • Thanks for your reply I'm going to research more about that. Commented Mar 10, 2017 at 15:23

1 Answer 1

1

The problem is that you are json_encode -ing your data twice. Try this:

$tempArray = array();
$ArrayUser = new ArrayUser(); 
foreach ($sth as $sth) {
       $user = new User();
       $user->id = $sth['id'];
       $user->nombre = $sth['name'];
       array_push($tempArray, $user);
}
$ArrayUser->usuarios = $tempArray;
$axX = json_encode($ArrayUser);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply, It's almost there, only the array ($tempArray) left a comma at the end, like that: ` { "usuarios": [ { "id": "1", "nombre": "Leandro Gado" } , { "id": "2", "nombre": "Aitor Tilla" } ], } ` How could I remove that comma?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.