gpt4 book ai didi

php - 如何在 CakePHP Controller 中获取格式化的 JSON 输出

转载 作者:行者123 更新时间:2023-11-29 04:07:49 25 4
gpt4 key购买 nike

我应该如何转换我的 JSON 输出。这样就可以使用 J Query 轻松地对其进行迭代。

我正在使用 CakePHP Controller 在 MySql 查询后生成 JSON

没有 Trick 的 CakePHP 有帮助吗?

我得到输出为

在 View 中输出

[{"8":"Young"},{"9":"Child"},{"10":"Old"},{"11":"Large"}]

我需要输出为

[{ "id":"8", "name": "Young" }, { "id": "9", "name": "Child" }, { "id": "10", "name": "Old" },{ "id":"11", "name": "Large" }]

Controller -> gettype 方法

 if ($this->RequestHandler->isAjax()) {
if(isset($this->request->data['typeid'])){
$listType= array();
$arrayOfIds = explode(',',$this->request->data['TypeIds']);
foreach($arrayOfIds as $TypeId) {
$listType[] = $this->Type->find('list', array(
'conditions' => array(
'Type.id' => $TypeId
),
'fields' => array('Type.name')
));
}
echo json_encode($listType);
}
}

View 中的 AJAX

var dataType = 'typeid='+ typeid+'&TypeIds='+ TypeIds;
var urlToGetType = absUrl+"gettype/";
$.ajax({
type: "post",
dataType: "json",
url: urlToGetType,
data: dataType,
success: function (resTypeData, status) {
console.log(resTypeData);
},
error: function (xhr, desc, err) {

}
});

最佳答案

好吧,我明白了为什么我的原始解决方案不起作用:您在 find() 上调用“列表”方法,它生成的输出为:

Array
(
[id] => 'displayValue',
[1] => 'displayValue1',
[2] => 'displayValue2',
)

改用 find('all') :

[ModelName] => Array
(
[id] => 83
[field1] => value1
[field2] => value2
[field3] => value3
)

然后再次设置以下内容:

'fields' => array('Type.id', 'Type.name')

这是 CakePHP Retrieving Your Data Documentation .

关于php - 如何在 CakePHP Controller 中获取格式化的 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com