Skip to content
Advertisement

How can I fetch results from a junction table and insert them as an array into a JSON object using PHP?

I have Articles with Categories in a mysql Database. I would like to print out all Articles with their corresponding Categories as JSON in PHP to fetch with my Vue-App.

I’m working with the following tables: Articles, Categories and Article_has_Category (junction table, many to many):

JavaScript

The following PHP-Code selects and prints all Articles for my Frontend to fetch:

JavaScript
JavaScript

Is it somehow possible to insert all Categories as an array into that JSON-Output?

JavaScript

Currently I’m building the desired object in my frontend first using “SELECT * FROM Articles;” to fetch all articles and then in a seperate call, fetching the corresponding categories by Article ID using the statement below:

JavaScript

Is there any solution combining the two statements and building the desired object directly in my PHP File?

Advertisement

Answer

Okay I solved this by assembling my own JSON in PHP, instead of using json_encode().

My code is not very pretty but I commented it a bit for you to understand:

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