View mysql query results in Master/Detail

Asked

Viewed 41 times

0

I have the following result of a consultation:

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

How do I echo to display the data like this:

categoria1
sub1
sub2
sub3
categoria2
sub1
sub2
categoria3
sub1

1 answer

1

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

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

That can be done so:

<?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>';
    }
}

Generates as 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.