H
H
hrustbb22020-02-20 18:57:56
PHP
hrustbb2, 2020-02-20 18:57:56

How to convert a two dimensional array returned by MySQL?

Colleagues, for example, there is a database with the following tables city, house with the following fields:

city:
-id
-name

house:
-id
-city_id
-heigh
-width


Having requested from the database information about all cities with houses in them, having joined two tables, we will get a flat, two-dimensional array at the output.

Are there more or less universal means to get an array of the form from such a two-dimensional array:

[
  id => 1,
  name => city1,
  house => [
    id => 1,
    heigh => 100,
    width => 200,
  ]
],
[
  id => 1,
  name => city1,
  house => [
    id => 2,
    heigh => 200,
    width => 300,
  ]
]


That is an array repeating the structure of the requested data?

UPD: By a more or less universal tool, I mean that the amount of nested data and nesting depth are not always known in advance. That is, at the input some configuration and a flat array, at the output an array with a certain structure.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
hrustbb2, 2020-03-07
@hrustbb2

For myself, I decided this: an article on Habré

F
FanatPHP, 2020-02-20
@FanatPHP

https://phpdelusions.net/pdo_examples/nested_array

S
Sergey, 2020-02-20
@KingstonKMS

Do you have one house in the city?
Still, house must be an array.
You will have to use a loop. Therefore, it is better to do this:
1. A selection of cities
2. For each city, make a selection of houses, create an array with city fields and add house with a selection of houses to it, and add the final array of the city to the general array.

A
Andrey Tsvetkov, 2020-02-20
@yellow79

Alternatively, use grouping and the right combination of functions like json_arrayagg and json_object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question