How to return json object with json array inside of it?
There's 2 way to do it:
- If you want to keep your query, you must parse the data first before you parse it to json.
...function regroup_color($data = array()){ $ret = array(); foreach($data as $d){ $id = $d['id']; if(!isset($ret[$id])){ $color = $d['color']; unset($d['color']); $ret[$id] = $d; $ret[$id]['color'][] = $color; }else{ $ret[$id]['color'][] = $d['color']; } } return $ret;}$data = regroup_color($data);echo json_encode($data)...
Or you could just...
- make the query 2 part, first is for get all
items
, second is for get thecolors
for it
...$query = "SELECT * FROM items";// get the data here using query above$data = {{result of query}};foreach($data as $i => $d){ $id = $d['id']; $query = "SELECT * FROM item_color JOIN colors ON item_color.color_id = colors.id"; // get the data here using query above $colors = {{result of query}}; foreach($colors as color){ $data[$i]['color'][] = $color['name']; }}echo json_encode($data)...
i wanted to add also category so this is what i came with
function regroup_color($data = array(),$data2 = array()){ // array that will hold our data and we will return it later$ret = array();// fetch the data as dforeach($data as $d){ //save the id $id = $d['id']; //make sure no id was set if(!isset($ret[$id])){ // save the name of the color $color = $d['color']; unset($d['color']); //save all the item data $ret[$id] = $d; // add color to color array $ret[$id]['color'][] = $color; }else{ // if wa alredy did all the above things just keep adding colors to color array $ret[$id]['color'][] = $d['color']; }} foreach($data2 as $d){ //save the id $id = $d['id']; //make sure no id was set if(!isset($ret[$id])){ // save the name of the color $category = $d['category']; unset($d['category']); $ret[$id] = $d; $ret[$id]['category'][] = $category; }else{ $ret[$id]['category'][] = $d['category']; } }
return $ret;}
result :
"22": {"id": "22","title": "my products 515151","descreption": "5454545455","price": "0.05","quantity": "2","date_added": "2021-01-29 14:37:24","primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg","color": [ "black", "white", "pink", "red", "yellow"],"category": [ "buttom", "hats", "shoes"]
}