Display mysql query results in Master / Detail

0

I have the following result of a query:

CATEGORIA  | SUB
cateroria1 - sub1
categoria1 - sub2
categoria1 - sub3
categoria2 - sub1
categoria2 - sub2
categoria3 - sub1

How do I echo the data like this:

categoria1
sub1
sub2
sub3
categoria2
sub1
sub2
categoria3
sub1
    
asked by anonymous 06.02.2018 / 22:30

1 answer

1

It is necessary to mount an array similar to the structure you want to display. Something similar to:

[
    'categoria1' => ['sub1', 'sub2', 'sub3', 'sub4'],
    'categoria2' => ['sub1', 'sub2', 'sub3', 'sub4']
]

What can be done like this:

<?php

//supondo que são duas colunas distintas (com indice númerico)
$dadosConsulta = [
    ['categoria1', 'sub1'],
    ['categoria1', 'sub2'],
    ['categoria1', 'sub3'],
    ['categoria2', 'sub1'],
    ['categoria2', 'sub2'],
    ['categoria1', 'sub1'],
    ['categoria3', 'sub1']
];

$dados = [];
for($i = 0; $i < count($dadosConsulta); $i++){
    $dados[$dadosConsulta[$i][0]][] = $dadosConsulta[$i][1];
}

//estrutura
var_dump($dados);

//percorrendo
foreach($dados as $categoria => $subcategorias){
    echo $categoria . '<br>';
    foreach($subcategorias as $subcategoria){
        echo $subcategoria . '<br>';
    }
}

Generate output:

array (size=3)
  'categoria1' => 
    array (size=4)
      0 => string 'sub1' (length=4)
      1 => string 'sub2' (length=4)
      2 => string 'sub3' (length=4)
      3 => string 'sub1' (length=4)
  'categoria2' => 
    array (size=2)
      0 => string 'sub1' (length=4)
      1 => string 'sub2' (length=4)
  'categoria3' => 
    array (size=1)
      0 => string 'sub1' (length=4)

categoria1
sub1
sub2
sub3
sub1
categoria2
sub1
sub2
categoria3
sub1
    
07.02.2018 / 01:15