0

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?

4

2 回答 2

2

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.

于 2013-05-11T20:22:10.440 回答
0

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

于 2013-05-11T20:22:50.877 回答