将多个结果放在一个数组中

时间:2014-12-11 04:04:03

标签: php mysql sql arrays pdo

我已经在sql中编写了代码,因为我只想了解这个概念。完成后我会将其更改为sqli / pdo。所以请忽略sql方法,并帮助我解决问题

我需要根据特定的catid列出所有vendorname。为此,我有2个表子类别和VendorSubCat。我试图通过首先根据catid获取subcatid(即子类别表中的id)来链接这两个表,然后根据从上一个表中选择的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","vendorname":"Zee Zone","vendorid":"2","subcatid":"7"}]}{"list":[{"id":"4","vendorname":"????? ????????","vendorid":"3","subcatid":"4"}]}

我希望将所有结果放在一个数组中,即所有列表都应该放在一个列表中。 &#34;列表&#34;每次显示新行时都不应显示。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您无需立即回复结果:

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