我需要在我的json中添加一個jsonArray,我使用一個php類(User.php)來建模json。像這樣:PHP如何將數組添加到Json而不是字符串
class User {
public $id = "";
public $nombre = "";
}
我使用其他類(ArrayUser.php)到陣列從類用戶添加到最終的JSON
class ArrayUser {
public $usuarios;
}
我以這種方式使用這些類在我的代碼:
$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);
結果是這樣的:
{
"usuarios": "[{"id":"1","nombre":"Leandro Gado"},{"id":"2","nombre":"Aitor Tilla"}]"
}
但我不希望像字符串數組(不通過的方式有效的JSON),其實我需要我的Json這樣的:
{
"usuarios": [{
"id": "1",
"nombre": "Leandro Gado"
}, {
"id": "2",
"nombre": "Aitor Tilla"
}]
}
我感謝你的幫助。 此致敬禮。
沒有像「json數組」那樣的東西。 [JSON](https://en.wikipedia.org/wiki/JSON)是一些數據結構的文本表示。建立你的數據結構,然後將它傳遞給['json_encode()'](http://php.net/manual/en/function.json-encode.php)不要編碼單個部分(btw,第二個參數' json_encode()是一個數字,不是「真」)。如果你想編碼爲JSON的數據結構是一個對象,那麼使它的類實現['JsonSerializable'](http://php.net/manual/en/class.jsonserializable.php)接口。這樣你可以控制哪些對象屬性被編碼以及如何編碼。 – axiac
感謝您的回覆,我將對此進行更多的研究。 – irvineff7