[英]place multiple result in a single array
我已經用sql編寫了代碼,因為我只是想了解這個概念。 完成后,我將其更改為sqli / pdo。 因此請忽略sql方法,請plz幫助我解決問題
我需要根據特定catid列出所有供應商名稱。 為此,我有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"}]}
我希望將所有結果放在一個數組中,即所有清單應歸入一個清單。 每次顯示新行時都不應該顯示“列表”。 任何幫助,將不勝感激
您無需立即回顯結果:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.