Question :
Well I have the following array:
$produtos2[] = array(
"cod" => (int) 768,
"nome" => "LOGITECH M535",
"GRUPO" => "MOUSE"
);
$produtos2[] = array(
"cod" => (int) 2334,
"nome" => "MULTILASER DECT",
"GRUPO" => "TECLADO"
);
$produtos2[] = array(
"cod" => (int) 334,
"nome" => "PANASONIC DECT",
"GRUPO" => "MOUSE"
);
$produtos2[] = array(
"cod" => (int) 3334,
"nome" => "APPLE DECT",
"GRUPO" => "TECLADO"
);
$produtos2[] = array(
"cod" => (int) 234,
"nome" => "SAMSUNG D499",
"GRUPO" => "MOUSE"
);
To list the result of the array I do this:
// Navega pelos elementos do array
foreach ($produtos as $c) {
echo $c['nome']."<br>";
}
The result is:
LOGITECH M535
MULTILASER DECT
PANASONIC DECT
APPLE DECT
SAMSUNG D499
Well what I need is to separate the products from having the same group and listing them by group, for example:
MOUSE
LOGITECH M535
PANASONIC DECT
SAMSUNG D499
TECLADO
MULTILASER DECT
APPLE DECT
I have no idea how to do this.
Answer :
Make a function to group:
function agrupar($array, $campoAgrupar) {
$resultado = array();
foreach($array as $valor) {
$resultado[$valor[$campoAgrupar]][] = $valor;
}
return $resultado;
}
Grouping by "GRUPO"
with the function indicated above generates the following array to you:
array(2) {
["MOUSE"]=>
array(3) {
[0]=>
array(3) {
["cod"]=>
int(768)
["nome"]=>
string(13) "LOGITECH M535"
["GRUPO"]=>
string(5) "MOUSE"
}
[1]=>
array(3) {
["cod"]=>
int(334)
["nome"]=>
string(14) "PANASONIC DECT"
["GRUPO"]=>
string(5) "MOUSE"
}
[2]=>
array(3) {
["cod"]=>
int(234)
["nome"]=>
string(12) "SAMSUNG D499"
["GRUPO"]=>
string(5) "MOUSE"
}
}
["TECLADO"]=>
array(2) {
[0]=>
array(3) {
["cod"]=>
int(2334)
["nome"]=>
string(15) "MULTILASER DECT"
["GRUPO"]=>
string(7) "TECLADO"
}
[1]=>
array(3) {
["cod"]=>
int(3334)
["nome"]=>
string(10) "APPLE DECT"
["GRUPO"]=>
string(7) "TECLADO"
}
}
}
See Ideone for grouping result
To show you how you want to use just two foreach
:
$produtosPorGrupo = agrupar($produtos2,"GRUPO");
foreach ($produtosPorGrupo as $nomeGrupo => $grupo){
echo $nomeGrupo . PHP_EOL;
foreach ($grupo as $prod){
echo "t" . $prod['nome']. PHP_EOL;
}
}
See also in Ideone the result already with 2 foreach
to show
Final output:
MOUSE
LOGITECH M535
PANASONIC DECT
SAMSUNG D499
TECLADO
MULTILASER DECT
APPLE DECT
Edit :
To sort by the grouped array, just use one of the functions already in the php that orders by key:
Soon it would look like this:
$produtosPorGrupo = agrupar($produtos2,"GRUPO");
ksort($produtosPorGrupo);
//resto do código para mostrar
Use array_column()
to get all available groups, then just make a foreach by passing the key as the current item (group) and value the complete item.
$grupos = array_column($produtos2, 'GRUPO');
$novo = array();
foreach ($produtos2 as $item){
$novo[$item['GRUPO']][] = $item;
}