如何在CakePHP控制器中获取Formatted JSON输出

时间:2014-07-23 20:25:14

标签: php jquery mysql json cakephp-2.0

如何转换我的 JSON 输出。 因此可以使用J Query轻松迭代。

我使用 CakePHP 控制器在 MySql 查询后生成 JSON

没有Trick,CakePHP中有任何帮助吗?

我的输出为

在视图中输出

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

我需要 输出为

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

控制器 - > 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);
        }
    }

视图中的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) {

    }
});

4 个答案:

答案 0 :(得分:3)

好吧,我弄清楚为什么我的原始解决方案不起作用:你正在调用“#list”列表' 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

答案 1 :(得分:1)

听起来你很近但却因json_encode的奇怪而被绊倒。让我们假设您从第一个对象开始作为PHP中的数组(为了参数,这是伪的)

['8'=>'young', '9'=>'child']

你要做的就是这个

$newar = [];
foreach($array as $key => $val) {
    $newar[] = ['id' => $key, 'name' => $val];
}
echo json_encode($newar);

请记住,PHP允许关联数组,而JS则不允许。因此,关联的PHP数组成为JS对象。

答案 2 :(得分:1)

我对CakePHP不熟悉,但从严格的PHP观点来看,你可以迭代它。

$string = '[{"8":"Young"},{"9":"Child"},{"10":"Old"},{"11":"Large"}]';

foreach (json_decode($string) as $obj) {
  foreach ($obj as $key => $value) {
    $temp[] = array(
      'id'   => $key,
      'name' => $value
    );
  }
}

echo "<pre><code>";
print_r(json_encode($temp));
echo "</code></pre>";

我确信您必须能够调整MySQL查询。我在调查。

修改

你最有可能把它放在这里:

foreach($arrayOfIds as $TypeId) {
  $listType[] = $this->Type->find('list', array(
    'conditions' => array(
      'Type.id' => $TypeId
    ),
    'fields' => array('Type.name')
  ));
}
foreach ($listType as $obj) {
  foreach ($obj as $key => $value) {
    $newListType[] = array(
      'id'   => $key,
      'name' => $value
    );
  }
}

echo json_encode($newListType);

在没有测试环境的情况下阅读docs,我能做的最好。

来自文档:

  

默认情况下,模型的主键用于键,显示字段(可使用模型属性displayField配置)用于值。

答案 3 :(得分:1)

将其从find('list'更改为find('all'会为您提供命名字段。