I have data in my database as
COl1 | COL2
fruit | apple, grape, berry
vegetable | tom, pot, leaf
If I query for fruit, I want COL2 to read for the query and data is split and output echo json_encode($data)
should be in the form of:
[
{input: "fruit", target: "apple"},
{input: "fruit", target: "grape"},
{input: "fruit", target: "berry"} ]
Any suggestions?
If your question is how to format the col2 value into your target JSON format. then do it like
$dbval = "apple, grape, berry";
$fruits = explode(",",$dbval);
$json = array();
foreach($fruits as $fruit) {
$json[] = array("input"=>"fruit","target"=>$fruit);
}
echo json_encode($json)
sorry if i got the question wrong.
You should re-think your database design. What do you think about tables like:
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
If you're not able to edit the database, try to explode the strings, modify the arrays as you want and encode them to JSON: http://php.net/manual/de/function.explode.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.