php – 将多个结果放在一个数组中
发布时间:2020-12-13 22:54:05 所属栏目:PHP教程 来源:网络整理
导读:我已经在sql中编写了代码,因为我只想了解这个概念.完成后我会将其更改为sqli / pdo.所以请忽略sql方法,并帮助我解决问题 我需要根据特定的catid列出所有vendorname.为此,我有2个表子类别和VendorSubCat.我试图通过首先根据catid获取subcatid(即id from subca
我已经在sql中编写了代码,因为我只想了解这个概念.完成后我会将其更改为sqli / pdo.所以请忽略sql方法,并帮助我解决问题
我需要根据特定的catid列出所有vendorname.为此,我有2个表子类别和VendorSubCat.我试图通过首先根据catid获取subcatid(即id from subcategory table)来链接这两个表,然后根据从上一个表中选择的subcatid(来自VendorSubCat表)显示供应商名称. 表视图子类别 id subcatname subcatdesc catname catid 表视图VendorSubCat vendorname vendorid subcatid 码 <?php ob_start(); require_once('config.php'); $catid = $_REQUEST['catid']; $sql1 = "SELECT * FROM subcategory where catid='" . $catid . "'"; $result1 = mysql_query($sql1); while ($row = mysql_fetch_array($result1)) { $myid = $row['id']; if (sql1 != '0') { $productt = mysql_query("select * from VendorSubCat where id = '" . $myid . "' "); $posts = array(); if (mysql_num_rows($productt)) { while ($post = mysql_fetch_assoc($productt)) { $posts[] = $post; } header('Content-type: application/json'); echo stripslashes(json_encode(array('list' => $posts))); } else { header('Content-type: application/json'); echo stripslashes(json_encode(array('list' => 'No productlist'))); } } } ?> 尽管代码工作正常,但结果显示在不同的数组中.它显示了这样的结果 {"list":[{"id":"1","vendorname":"Marzoogah","vendorid":"1","subcatid":"4"}]}{"list":[{"id":"2","vendorname":"Zee Zone","vendorid":"2","subcatid":"4"}]}{"list":[{"id":"3","subcatid":"7"}]}{"list":[{"id":"4","vendorname":"????? ????????","vendorid":"3","subcatid":"4"}]} 我希望将所有结果放在一个数组中,即所有列表都应该放在一个列表中.每次显示新行时都不应显示“list”.任何帮助,将不胜感激 解决方法
您无需立即回显结果:
echo stripslashes(json_encode(array('list' => $posts))); 而是将所有数据收集到一个数组: $results = array(); //Your code $results[] = array('list' => $posts); //... $results[] = array('list' => 'No product list'); //... //And echo just one time in the end: echo stripslashes(json_encode($results); 或类似的东西用于合并: $results = array(); //Your code $results = $results + $posts; //... $results = 'No product list'; //... //And echo just one time in the end: echo stripslashes(json_encode(array('list' => $results))); 此外,您可以在没有递归查询的情况下执行数据库请求; 就像是: SELECT vsc.* FROM VendorSubCat vsc INNER JOIN subcategory sc ON vsc.id=sc.id WHERE sc.cat_id = 15 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |