如何将序列化的 JSON 视图数据输出为对象数组,而不是包装在外部对象中? [英] How to output serialized JSON view data as an array of objects, instead of wrapped in an outer object?
问题描述
我正在将 CakePHP 数组的返回值转换为 JSON,目前是这样的:
<代码>{平台用户":[{id":1",名称":用户 1"},{"id" : "3",名称":用户 3"}]}
我希望它是这样的:
<预><代码>[{id":1",名称":用户 1"},{"id" : "3",名称":用户 3"}]我正在尝试 Set::extract('{n}.Model', $data) Hash::extract('{n}.Model',$data) 一点运气都没有.
完整代码:
$platformusers = $this->Platformuser->find('all', array('字段' =>数组('平台用户.id', '平台用户.name')));$platformusers = Hash::extract('{n}.Platformuser', $platformusers);$this->set(数组('平台用户' =>$平台用户,'_序列化' =>数组('平台用户')));
为 _serialize
选项设置一个 string
而不是 array
.array
表示可能有多个视图变量需要序列化,这需要将它们打包到单独的对象属性中.
$this->set(array('平台用户' =>$平台用户,'_序列化' =>'平台用户'));
这应该会给你想要的结果.
I am converting the returning value of CakePHP array to JSON, currently its like this:
{
"platformusers" : [
{
"id" : "1",
"name" : "user1"
},
{
"id" : "3",
"name" : "user3"
}
]
}
And I want it to be like this:
[
{
"id" : "1",
"name" : "user1"
},
{
"id" : "3",
"name" : "user3"
}
]
I am trying with Set::extract('{n}.Model', $data) Hash::extract('{n}.Model', $data) with no luck at all.
Full code:
$platformusers = $this->Platformuser->find('all', array(
'fields' => array('Platformuser.id', 'Platformuser.name')
));
$platformusers = Hash::extract('{n}.Platformuser', $platformusers);
$this->set(array(
'platformusers' => $platformusers,
'_serialize' => array('platformusers')
));
Set a string
for the _serialize
option instead of an array
. An array
indicates that there might be multiple view vars that need to be serialized, and that requires them to be packed into separate object properties.
$this->set(array(
'platformusers' => $platformusers,
'_serialize' => 'platformusers'
));
That should give you the desired result.
这篇关于如何将序列化的 JSON 视图数据输出为对象数组,而不是包装在外部对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!