I can't find a good title for my question. I'm doing a Restful API /JSON
My problem is:
I have got two tables:
Product: id, name
Prices: id_product, price
Product 1--* Prices (One product have got multiples prices)
So, If I want to export the next information in JSON
products: [
{
id:1
name: chair
prices: [3.3,5.0,6.0]
}
, {
id:2
name: apple
prices: [2.0,5.0]
} ,..
]
I do the next query:
SELECT product.id, product.name, prices.price FROM procut LEFT JOIN prices ON product.id = prices.id_product
I got the next result:
id , name , prices
----------------------
1 chair 3.3
1 chair 5.0
1 chair 6.0
2 apple ...
...
I use PHP, codeigniter. Is there a way to transform in a well form JSON? Because I have to rebuild the result, doing:
$resultArray = $query->result_array(); //CodeIgniter
foreach($resultArray as $row)
{
if(!isset($resultData[$row['id']]))
{
$resultData[$row['id']] = $row;
unset($resultData[$row['id']]['price']);
$resultData[$row['id']]['prices'] = array();
}
$resultData[$row['id']]['prices'][] = $row['price'];
}
to create the JSON well formed