2017-03-09 42 views
1

我需要在我的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" 
    }] 
} 

我感谢你的帮助。 此致敬礼。

+4

没有像“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

+0

感谢您的回复,我将对此进行更多的研究。 – irvineff7

回答

1

问题是你是json_encode-你的数据两次。试试这个:

$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); 
+0

感谢您的回复,这是几乎没有,只有数组($ tempArray)结尾留下了一个逗号,这样的: ' { “USUARIOS”: { “ID”: “1”, “农布雷”: “林德罗加多” } , { “ID”: “2”, “农布雷”: “的Aitor椴” } ], } ' 我怎么能删除逗号? – irvineff7

相关问题