How to generate json response using php

前端 未结 2 1440
余生分开走
余生分开走 2021-01-16 12:23

How to generate json response using php

In the model:

public function groups($getGroupId) {
        $cols = array(\'group_id\',\'name\');
        $sq         


        
相关标签:
2条回答
  • 2021-01-16 13:08

    I would recommend that you use the output from json_encode as it is. Takes less bandwidth. Only reason I see for all the whitespace is for debugging, and for that I'd rather use FireBug and/or JSONView in FireFox.

    Anyways, if you really want to, you can maybe try the JSON_PRETTY_PRINT flag? Seems this was added in 5.4.0 though, so maybe not the version you're on supports it... There seems to be options you can use for that in the comments there though. Maybe you can find something useful? http://www.php.net/manual/en/function.json-encode.php#102091


    You say you have to create a jstree now, and that doesn't really have anything to do with what you're asking. You're two examples of data doesn't look anything alike at all. json_encode does not do anything special or magic. It just takes data and turns it into JSON. It's your job to make that data look correctly first, before encoding it. Your DB query most likely returns a set of flat rows, and you'll have to loop through it and somehow generate your tree the way you want it. You can probably find other questions here about how to create tree structures out of flat DB results.

    0 讨论(0)
  • 2021-01-16 13:19

    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() and Zend_Json::encode() will allow you to encode and decode Json and prettyPrint() is used to make your output prettier.


    Edit: 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.

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

    0 讨论(0)
提交回复
热议问题