CakePHP的阵列格式 [英] CakePHP array format

查看:125
本文介绍了CakePHP的阵列格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的CakePHP阵列的返回值转换成JSON,目前它是这样的:

  {
  platformusers:[
    {
      ID:1
      名:USER1
    },
    {
      ID:3
      名:用户3
    }
  ]
}

和我希望它是这样的:

  [
    {
      ID:1
      名:USER1
    },
    {
      ID:3
      名:用户3
    }
]

我想用的 设置::提取物('{N}。型号',$数据) 的哈希::提取物('{N}。型号, $的数据),没有运气可言。

全部code:

  $ platformusers = $这个 - > Platformuser->找到('所有',阵列(
        '域'=>阵列('Platformuser.id','Platformuser.name')
    ));    $ platformusers =哈希::提取物('{N} .Platformuser',$ platformusers);    $这个 - >设置(阵列(
        platformusers'=> $ platformusers,
        _serialize'=>阵列('platformusers')
    ));


解决方案

设置字符串 _serialize 选项代替阵列。一个阵列表示,有可能是需要进行序列化视图增值分销商,这需要它们被打包成独立的对象属性。

  $这个 - >设置(阵列(
    platformusers'=> $ platformusers,
    _serialize'=> platformusers
));

这应该给你想要的结果。

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.

这篇关于CakePHP的阵列格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆