PHP associative arrays

1

I'm trying to create an array of a mysql query and I'm going crazy. That query returns me several machines by centers. And I want to make an array with the centers that have and within each center the different machines

foreach ($maquinas as $row){
        $centros['centros'][$row->id_centro] = $row->nombre;                
}

So far, well, but I do not know how to get inside each center to create an array with the different machines.

This is the mysql query:

SELECT maquinas.*, centro.* from maquinas JOIN centro_maquinas ON centro_maquinas.id_maquina = maquinas.id_maquina JOIN centro ON centro.id_centro = centro_maquinas.id_centro ORDER BY id_centro

Returns several rows each with the id of the center, the id of the machine ...

    
asked by Iagonzalez 17.04.2018 в 09:05
source

1 answer

2

Assuming that the array $ machines has the id of the center, the one of the machine and the name of the machine, I think you could do something like:

foreach($maquinas as $row) {
    $centros['centros'][$row->id_centro][] = $row->nombre;
}

that is, you would miss the final array [] so that as we go through each row, add the element within that array (with the key $ row- > id_centro)

Note that this solution assumes that your rows are of the type:

id_fila    id_centro   id_maquina   nombre
   1          1            1          nombre_maquina1
   2          1            2          nombre_maquina2
   3          2            5          nombre_maquina3
   4          2            6          nombre_maquina6
    
answered by 17.04.2018 в 09:15