Join Table To a nested array [PHP/MYSQL]

我的梦境 提交于 2019-12-11 14:07:58

问题


How to select join multiple tables and get it in a nested array easily?

For Example

Table 1 -School: SchoolID, SchoolName,PrincipalID
Talbe 2 - Principal: PrincipalID,PrincipalName

I want to get a nested array in PHP like

"School": [
            {
                "SchoolID": "7",
                "SchoolName": "New",
                "Principal": {
                      "PrincipalID":"1",
                      "PrincipalName":"James"
                }
            }

The problem is, how to get the nested array use a automatic way instead of specifying each field and add it into a array manually? without even kowning the actual field names, just nesting multiple tables into a nested array.


回答1:


the result of the query can be a single dimension array only. so in other words, you can't create a multidimensional result. You need to do that in the application level, (use your own logic) but there's a function that can help you sometime. It's called GROUP_CONCAT. What it does it is it concatenates its row values into single row and separated by a comma.

  • GROUP_CONCAT
  • GROP_CONCAT example


来源:https://stackoverflow.com/questions/13437378/join-table-to-a-nested-array-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!