Skip to content
Advertisement

Merge MY SQL query result with multiple rows for same item id into single row for json response

I am new to PHP and WordPress. I am trying to build a custom API on WordPress. I have a My Sql query that uses INNER JOIN to join 2 tables and returns multiple rows for same item Id. I am then trying to convert the result set into a JSON response.

The problem is i am getting a new JSON object for each item Id even if the Ids are same.

Please see the My SQL query below:

JavaScript

Php code:

JavaScript

JSON result looks like:

JavaScript

As you can see, the id value is repeating and so is Title. I want the response to be something like

JavaScript

Any help with the query or at the Php code level will be useful.

Advertisement

Answer

Change your loop to this:

JavaScript

This will group the nested array by id and title (I’m assuming that title is the same for the same id).

$data would now contain

JavaScript

See demo

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