我如何得到json响应从PHP格式下?

sai*_*ram 5 php mysql json

我有两个表,在yearselection两列中,在那里有testtable2三列,基于在第二个表中使用的第一个表id.,我想使用php,这两个表显示json响应如下.

yearselection:

   id   year
    6   2014-2015
    2   2010-2011
    3   2011-2012
    4   2012-2013
    5   2013-2014
    1   2009-2010
    7   2015-2016
Run Code Online (Sandbox Code Playgroud)

testtable2:

id   name    yearselection
1    test1        2
2    test2        1
3    test3        1 
4    test4        1
5    test5        2
6    test6        3 
Run Code Online (Sandbox Code Playgroud)

我希望以json格式显示如下:

   {
    "2009-2010": [

        {
            "id": "2",
            "name": "test2"
        },

        {
            "id": "3",
            "name": "test3"
        },

        {
            "id": "4",
            "name": "test4"
        }

    ],
    "2010-2011": [

        {
            "id": "1",
            "name": "test1"
        },

        {
            "id": "5",
            "name": "test5"
        }

    ],
    "2011-2012": [

        {
            "id": "6",
            "name": "test6"
        }

    ]
}
Run Code Online (Sandbox Code Playgroud)

mycode的

public function actionArchives()
    {
    //echo $keyword=$_POST['keyword'];

        $query= Yii::app()->db->createCommand("select * from yearselection ORDER BY id ASC")->queryAll();
        $arr = array();
        if(count($query) > 0) {

        foreach ($query as $queryElement) {

        $query2= Yii::app()->db->createCommand("select * from testtable2 where yearselection='".$queryElement['id']."' ORDER BY id ASC")->queryAll();




        $arr[] = $queryElement;
        }
        }

        # JSON-encode the response
        $json_response = json_encode($arr);

        // # Return the response
        echo $json_response;


    //exit;
    }
Run Code Online (Sandbox Code Playgroud)

Abb*_*bas 3

你先这样写你的查询

public function actionArchives()
{
//echo $keyword=$_POST['keyword'];

    $query= Yii::app()->db->createCommand("SELECT y.year,y.id as year_id,t.id as test_id,t.name 
    FROM yearselection as y JOIN testtable2 as t
    ON y.id=t.yearselection")->queryAll();
    $arr=array();
    if(count($query) > 0)
    {
      $arr = $query;
     // Now you run loop to change indexes of array,i.e.
      $count=count($arr);
      for($i=0;$i<$count;$i++)
      {
        $year=$arr[$i]['year'];
        $arr[$year]=$arr[$i];
        unset($arr[$i]);
      }
     // Now your array has index as your year column,
    }

    # JSON-encode the response
    $json_response = json_encode($arr);

    // # Return the response
    echo $json_response;


//exit;
}
Run Code Online (Sandbox Code Playgroud)

现在,一旦您编写了上述查询,您将获得包含年份、year_id、test_id、name列的数据

现在,您已经将整个数据放入数组中,就像上面在变量中所做的那样$arr[](不接触$query变量来保留查询数据)。

现在你可以简单地做 json_encode($arr);

笔记:-

请不要在循环中点击 DB,就好像你的循环长度假设为 100 那么它将点击 DB 100 次。因此,您可以在这些情况下应用 JOINS,以便它根据单个参数从 2 个表中获取数据。

希望这能解决您的疑问。