Skip to content
Advertisement

From database via join to REST how does it work?

I have a database with two tables (orders & orderProducts) with 1:n-Relation. I would like to combine this two tables to give a JSON to my REST-Tool.

For this I have the following SQL-Query:

JavaScript

Here I will get this Array back:

JavaScript

I would like to have the following JSON:

JavaScript

For this I’am using the following working PHP code:

JavaScript

I’am a bit unsecure why this seems to be very complicated. Isn’t there any more convienience way to achive this? (With an other query maybe).

Advertisement

Answer

An easy way to group data is to use a “shared” key (here, the user id), initialize the row the first time you meet the user id, then, add the products to the ‘product’ key.

JavaScript

demo

You can also use array_filter :

JavaScript

demo

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement