我有两个表,在年度选择中有两列是在那里,在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@H_404_9@
testtable2:
ID name yearselection1 test1 22 test2 13 test3 1 4 test4 15 test5 26 test6 3 @H_404_9@
我希望以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" } ]}@H_404_9@
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; }@H_404_9@
最佳答案你是先写这样的查询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;}@H_404_9@
现在,一旦您编写了上述查询,您将获得包含year,year_ID,test_ID,name列的数据
现在你已经在变量$arr []中完成了数组中的整个数据(不接触$query varible来保存查询数据).
现在你可以做简单的Json_encode($arr);
注意:-
Please don’t hit DB in a loop as if your loop length is suppose 100 then it
will hit DB 100 times. So you can apply JOINS in those cases so that
it will take data from 2 tables based on a single parameter.
希望这能解决您的疑问. 总结
以上是内存溢出为你收集整理的我如何得到json响应从PHP格式下?全部内容,希望文章能够帮你解决我如何得到json响应从PHP格式下?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)