Skip to content
Advertisement

PHP: Best practise / API Function to consolidate SQL data 1:N to a 2d array

I often come across a situation where I have a 1:N relation, e.g. a table of items and another table with additional metadata / attributes for every item.

Consider this example:

JavaScript

Now I have two questions: I want to select extended user-data, every (uid, field_id) combination is unique, usually I do it this way:

JavaScript

I get a row for every user/field combination and would need to “re-sort” in php because usually I want to have an array which contains every User with a Subarray of extended attributes, for example like this:

JavaScript

Is there a standardized way of simplifying this and/or what’s the best-practise in such cases? Is there already something build-in in PHP (not an external SQL framework)?

Thanks

Advertisement

Answer

Something like this should work (didn’t test, sorry)

JavaScript

This is not generic code, you should adapt it for each table schema, but I do not know a simplier way to do it. Or you spam your SQL server by not doing “JOIN” query… :/ (I think your sql is better 🙂 )

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