CakePHP API返回如下结果:
{
"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 :(得分:2)
您可以使用其内置的Hash
实用程序操作CakePHP的数组格式: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);
然后你可以使用Hash :: expand来获取原始数组,现在格式化你想要的方式:
$results = Hash::expand(array_combine($keys, array_values($results)));
答案 1 :(得分:0)
我不认为CakePHP支持这一点。如果您想以简单的方式执行此操作,请检查“设置实用程序”。
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html