如何使用php生成json响应 [英] How to generate json response using php

查看:275
本文介绍了如何使用php生成json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用php生成json响应

How to generate json response using php

在模型中:

public function groups($getGroupId) {
        $cols = array('group_id','name');
        $sql = $this->select ()
                    ->from ( $this->_name, $cols )
                    ->where ( 'parent_id=?', $getGroupId );
        $groupDetails = $this->fetchAll ( $sql );
        //$childGroupName = $groupDetails['name'];
        return $groupDetails;
}

groupDetails.php页面:

groupDetails.php page:

$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
print_r($jsonResponse);

在打印数据时,我会得到这样的响应

When printing the data i'm getting response like this

[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]  

但是我想要这样的输出,因为我必须使用json生成jstree

But i want output like this, Because i have to generate a jstree using json

[
   {
      "data" : {
         "icon" : <optional>,
         "title" : <node name>
      },
      "attr" : {
         "rel" : <the type you defined in the js (maybe "group")>,
         "title" : <node title>,
         "id" : <the node's id / group id>
      },
      "state" : "closed"
   }
]

推荐答案

由于您使用的是Zend Framework,因此建议您使用

Since you are using Zend Framework, I recommend you to use Zend_Json. Zend_Json is a pretty useful component to use in order to format Json from any supported format (object, array, xml...).

Zend_Json::decode()Zend_Json::encode()将允许您对Json进行编码和解码,而prettyPrint()用于使输出更漂亮.

Zend_Json::decode() and Zend_Json::encode() will allow you to encode and decode Json and prettyPrint() is used to make your output prettier.

修改: 正如Svish所说,您的两个示例看起来并不相似,因此很难猜测您想在树中放入什么.

As Svish said, your two examples doesn't look alike, so it's kind of hard to guess what you want to put inside your tree.

您需要创建自己的数组,以便使它看起来像您想要的方式.

What you need is to create your own array, so you can make it look like the way you want.

例如,假设您只希望树中数据库中的一行,那么您的数组将是这样的:

For example, let's say you only want one row from your database in your tree, then your array would be something like this:

$v = array(
       array(
         "data" => array("icon" => "ICON",
                         "title" => $row->name),
         "attr" => array("rel" => "REL",
                         "title" => "TITLE", 
                         "id" => $row->group_id),
          "state" =>     "closed"));
echo Zend_Json::encode($v);

这些行应与您的示例类似.

These lines should echo something like in your examples.

要使其与您的 fetchAll() 一起使用,一个简单的 foreach 即可做到.

To make it works with your fetchAll(), a simple foreach will do it.

这篇关于如何使用php生成json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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