我正在寻找一些帮助来构建将在SQL查询输出中使用的通用PHP函数的帮助
从表中选择DISTINCT categoryID,StatusID,COUNT(*)A GROUP BY categoryID
样本结果:
categoryID StatusID COUNT(*) 类别B保留1 A类搁置4 C类保留3 B类草案1
数据库中可以有任意数量的CategoryID和状态...
并返回TABULAR表格式:
我想要的结果是这样的:
状态摘要表(按类别): -------------------------------------------------- ------- | 类别A | 类别B | CategoryC | ... | 全部的 已完成 0 | 1 | 0 | ... | 1个 暂停中| 4 | 0 | 3 | ... | 7 草稿| 0 | 1 | 1 | ... | 2个 -------------------------------------------------- ------- 总计:| 4 | 2 | 4 | ... | 10
我知道了!-我希望这会在将来对其他人有所帮助。这不是漂亮的代码,但是它可以工作,并且它很遗传,因此可以根据需要使用。
$ sql =“ SELECT DISTINCT categoryID,statusID,COUNT(*)作为Count1 FROM条目GROUP BY categoryID”; $ results = mysql_query($ sql,$ con); //现在我们有了状态和类别,让我们将计数放在正确的单元格中: echo displayTabularSum($ myarray,“ status”,“ category”,1);
现在,我使用的功能是:
函数displayTabularSum($ myarray,$ table1,$ table2,$ includeTotals) { //首先将所有数据从$ table1获取到数组中 $ sql =“ SELECT * FROM $ table1在哪里1”; $ results = mysql_query($ sql); $ statusCodes = getsqlresultintoarray($ results); //第二:将所有数据从$ table2获取到数组中 $ sql =“ SELECT * FROM $ table2在哪里1”; $ results = mysql_query($ sql); $ categoryCodes = getsqlresultintoarray($ results); //现在使用列中的适当值创建结果表 $ statusTable = array(); $ out =''; $ first = true; $ cT = array(); 为($ x = 0; $ x'; for($ y = 0; $ y'。$ categoryCodes [$ y] [1]。''; } if($ includeTotals)$ out。='总计'; $ out。=''; $ first = false; } $ out。=“”; $ out。=“”。$ statusCodes [$ x] [1]。“”; $ rT = 0; 为($ y = 0; $ y“; $ c1 = searchForId($ categoryCodes [$ y] [0],$ myarray,“ categoryID”); $ c2 = searchForId($ statusCodes [$ x] [0],$ myarray,“ statusID”); $ count1 = 0; $ same =($ c1 == $ c2); 如果($ same){ 如果($ c1 == 99999或$ c2 == 99999){ //不执行任何操作...这些为NULL } 别的 { $ count1 = $ count1 + $ myarray [$ c1] ['Count1']; } } $ out。= $ count1; $ rT = $ count1 + $ rT; $ cT [$ y] = $ cT [$ y] + $ count1; //收集列总计 $ out。=“”; } 如果($ includeTotals)$ out。=''。$ rT。''; //显示rowTotal $ out。=“”; } if($ includeTotals){//关闭表格前显示总计列。 $ cT1 = 0; $ out。=“”; $ out。='总计:'; 为($ x = 0; $ x'。$ cT [$ x]。''; $ cT1 = $ cT1 + $ cT [$ x]; } $ out。=''。$ cT1。''; $ out。=“”; } $ out。=“”; 返回$ out; } 函数getresultsintoarray1($ results) {//将所有结果从SQL QUery获取到数组的函数。 $ num_rows = mysql_num_rows($ results); $ myarray = array(); 如果($ num_rows> 0){ while($ row = mysql_fetch_assoc($ results)) { $ myarray [] = $ row; } }别的 { 回显“在数据库上找不到数据...”; unset($ myarray); $ myarray = array(); } 返回$ myarray; } 函数getsqlresultintoarray($ get)//是 { $ num_rows = mysql_num_rows($ get); $ returnArray = array(); $ i = 0; while($ row1 = mysql_fetch_array($ get)){ $ returnArray [$ i] [0] = $ row1 [0]; //这是ID $ returnArray [$ i] [1] = $ row1 [1]; //这是名字 $ i ++; } return $ returnArray; } 函数searchForId($ id,$ array,$ field) { 如果(count($ array)> 0){ foreach($ array as $ key => $ val){ 如果($ val [$ field] === $ id){ 返回$ key; } } } 返回99999; }
如果有人对如何改进有任何想法,我将不胜感激!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句