gpt4 book ai didi

php - PHP 中两个 mysql 表的 Json 需要按层次结构输出

转载 作者:行者123 更新时间:2023-11-29 19:01:19 24 4
gpt4 key购买 nike

我有两张 table ,

1 - 类别

2 - 子类别

 Category (table 1)
---------------
Cid | Name

1 | Vegetable

2 | Fruit


SubCategory (table 2)
----------------
Cid | Sid | S_name

1 | 1 | Carrot

1 | 2 | Beans

2 | 3 | Mango

我想要 Json 中的结果:-

  -> Category found

-> Vegetable

-> carrot

-> beans

-> Fruit

-> mango

我正在使用下面的代码!任何人都可以帮助我纠正我的代码并获得像我上面提到的那样的输出!我尝试了很多次。但没有得到解决方案!请帮助我获得类似目录形式的输出。谢谢

`$srtResult = "SELECT * FROM `category` `c` LEFT JOIN `subcategory` `s` ON 
(`c`.`cid` = `s`.`cid`)";

//Execute Qu**strong text**ery
$result=mysql_query($srtResult);
//Iterate Throught The Results

while ($row = mysql_fetch_assoc($result, MYSQL_ASSOC))
{ $count = $row['cid'];
while($row['cid'] = $count)
{ $subcatitem[] = Array( "cid" => $row['cid'], "sid" =>$row['sid'],
"sname" => $row['sc_name'] );
}
$json['category'][] = Array("category" => Array( "cid" => $row['cid'],
"name" => $row['name'], "subcategory" => Array( $subcatitem)));
}

header('Content-type: application/json');
echo json_encode($json);`

最佳答案

这还不够吗?

$srtResult = "SELECT * FROM `category` `c` LEFT JOIN `subcategory` `s` ON 
(`c`.`cid` = `s`.`cid`)";
$result = mysql_query($srtResult);

while ($row = mysql_fetch_assoc($result, MYSQL_ASSOC)) {
$json['category'][$row['name']] = $row['sc_name'];
}

header('Content-type: application/json');
echo json_encode($json);

编辑:

在注释中进行更多解释后,所需的 PHP 数组结构(给出预期的 JSON 字符串)应如下所示:

Array
(
[success] => 1
[message] => Category found in Database
[Category] => Array
(
[0] => Array
(
[id] => 1
[name] => vegetable
[Subcategory] => Array
(
[0] => Array
(
[cid] => 1
[sid] => 1
[sc_name] => carrot
)

[1] => Array
(
[cid] => 1
[sid] => 2
[sc_name] => beans
)

)

)

[1] => Array
(
[id] => 2
[name] => Fruit
[Subcategory] => Array
(
[0] => Array
(
[cid] => 1
[sid] => 1
[sc_name] => Mango
)

)

)

)

)

关于php - PHP 中两个 mysql 表的 Json 需要按层次结构输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43860005/

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