来自PHP的JSON输出
我的数据库中的数据如下所示来自PHP的JSON输出,php,mysql,json,Php,Mysql,Json,我的数据库中的数据如下所示 COl1 | COL2 fruit | apple, grape, berry vegetable | tom, pot, leaf 如果我查询水果,我希望COL2为查询读取数据,并拆分数据,输出echo json\u encode($data)的形式应为: [ {input: "fruit", target: "apple"}, {input: "fruit", target: "grape"}, {input: "fruit", t
COl1 | COL2
fruit | apple, grape, berry
vegetable | tom, pot, leaf
如果我查询水果,我希望COL2为查询读取数据,并拆分数据,输出echo json\u encode($data)
的形式应为:
[
{input: "fruit", target: "apple"},
{input: "fruit", target: "grape"},
{input: "fruit", target: "berry"} ]
有什么建议吗?如果您的问题是如何将col2值格式化为目标JSON格式。 那就这样做吧
$dbval = "apple, grape, berry";
$fruits = explode(",",$dbval);
$json = array();
foreach($fruits as $fruit) {
$json[] = array("input"=>"fruit","target"=>$fruit);
}
echo json_encode($json)
对不起,如果我答错了。您应该重新考虑您的数据库设计。您对以下表格有何看法:
category
- id
- name (e.q. fruit or vegetable)
food
- id
- name (e.q. apple, tom, pot, leaf, ...)
food_has_category
- id (if necessary)
- category_id
- food_id
如果无法编辑数据库,请尝试分解字符串,根据需要修改数组并将其编码为JSON:我觉得您的数据库没有遵循任何规范化规则的原因..始终提供您尝试过的内容的信息..因为在您实际尝试任何操作之前您不会了解..这里说的是一种方法,您必须迭代db行分解您的值并分配给新数组,然后将其发送给json(当然,西红柿也是水果:)