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?

3
  • some reason I feel your database does not follow any rules of Normalization.. Commented May 11, 2013 at 20:16
  • Always provide information on what you have tried..cause you won't learn until you actually attempted anything..that said here is one way you will have to iterate through db rows explode your values and assign to new array and than send it to json_decode Commented May 11, 2013 at 20:17
  • Of course, Tomatoes are fruit, too :) Commented May 11, 2013 at 20:24

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.