2014-10-20 129 views
0

CakePHP的API返回结果是这样的:如何从CakePHP中的对象中移除嵌套对象?

{ 
    "status": "OK", 
    "themes": [ 
     { 
      "Theme": { 
       "id": "20", 
       "user_id": "50", 
       "name": "dwdwdw", 
       "language_code_from": "cz", 
       "language_code_to": "en", 
       "type": "CUSTOM", 
       "created": "2014-10-19 15:36:05", 
       "count_of_cards": 0 
      } 
     } 
    ] 
} 

我想问一下,在删除怎么能嵌套主题对象,以获取导致这样?:

{ 
    "status": "OK", 
    "themes": [ 
     { 
       "id": "20", 
       "user_id": "50", 
       "name": "dwdwdw", 
       "language_code_from": "cz", 
       "language_code_to": "en", 
       "type": "CUSTOM", 
       "created": "2014-10-19 15:36:05", 
       "count_of_cards": 0 
     } 
    ] 
} 

这里是我的CakePHP代码:

$this->Theme->recursive = -1; 
         // GET USER ID 
         $themeData['user_id'] = $isSessionValid; 
         // GET ALL THEMES RELATED TO USER 
         $foundThemes = $this->Theme->find('all', array(
           'conditions' => array(
            'Theme.user_id' => $themeData['user_id']) 
          ) 
         ); 
         $themes = array(); 
         // FOREACH THEMES AND GET COUNT FOR CARDS FOR EACH THEME 
         foreach($foundThemes as $foundTheme) { 
          // GET COUNT OF QUESTIONS FOR ACTUAL THEME 
          $countOfCards = $this->Theme->Card->find('count', array(
           'conditions' => array(
            'Card.theme_id' => $foundTheme['Theme']['id']) 
           ) 
          ); 
          // APPEND TO ACTUAL ARRAY 
          $foundTheme['Theme']['count_of_cards'] = $countOfCards; 
          array_push($themes,$foundTheme); 
         } 

         // SET SUCCESS RESPOSNSE 
         $this->set(array(
          'status' => 'OK', 
          'themes' => $themes, 
          '_serialize' => array(
           'status', 
           'themes', 
          ) 
         )); 

非常感谢您的任何建议。

+0

你是说你不喜欢值'set'回到你的视图?如果是这样 - 你是否尝试将_themes_键更改为''themes'=> $ themes ['Theme']' – AgRizzo 2014-10-20 21:21:00

回答

2

可以使用操纵CakePHP的阵列格式内置在Hash实用程序:http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash

我会做的是扁平化的结果:

$results = Hash::flatten($results); 

你的数据阵列将结束看起来像这样的单维阵列:

$results = array(
    'status' => 'OK' 
    'themes.0.Theme.id' => 20, 
    ... 
    'themes.1.Theme.id' => 21, 
    ... 
); 

然后可以使用字符串替换从您的键删除“主题”:

$keys = array_keys($results); 
$keys = str_replace('Theme.', '', $keys); 

然后你可以使用哈希::扩展,让您的原始数组,现在格式化你怎么想:

$results = Hash::expand(array_combine($keys, array_values($results)));