gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:39:29 25 4
gpt4 key购买 nike

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

我需要根据特定的 catid 列出所有供应商名称。为此,我有 2 个表子类别和 VendorSubCat。我试图通过首先根据 catid 获取 subcatid(即来自 subcategory 表中的 id),然后根据从上一个表中选择的 subcatid(来自 VendorSubCat 表)显示供应商名称来链接这两个表。

表 View 子类别

id  subcatname  subcatdesc  catname catid

表 View 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

关于php - 将多个结果放在一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27415177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com