I have the following problem.
I have an array returned from the database that looks like this:
array(4) {
[0]=>
array(4) {
["groupoURL"]=> string(7) "express"
["grupoNome"]=> string(13) "Express"
["subgrupoURL"]=> string(4) "aves"
["subgrupoNome"]=> string(4) "Aves"
}
[1]=>
array(4) {
["groupoURL"]=> string(7) "express"
["grupoNome"]=> string(13) "Express"
["subgrupoURL"]=> string(4) "peixes"
["subgrupoNome"]=> string(4) "Peixes"
}
[2]=>
array(4) {
["groupoURL"]=> string(7) "executivo"
["grupoNome"]=> string(13) "Executivo"
["subgrupoURL"]=> string(4) "aves"
["subgrupoNome"]=> string(4) "Aves"
}
[3]=>
array(4) {
["groupoURL"]=> string(7) "executivo"
["grupoNome"]=> string(13) "Executivo"
["subgrupoURL"]=> string(4) "carnes"
["subgrupoNome"]=> string(4) "Carnes"
}
}
I'm trying to merge values that are identical (In this case, the "groupURL" and "groupName" keys will always be the keys, and the rest "subgroupHRL" and "subgroupName" will become an array and their values will be joined.
My end result would need to look like this:
array(2) {
[0]=>
array(3) {
["groupoURL"]=> string(7) "express"
["grupoNome"]=> string(13) "Express"
["subgrupos"]=> array(
array(
["subgrupoURL"]=> "aves",
["subgrupoNome"]=> "Aves"
),
array(
["subgrupoURL"]=> "peixes",
["subgrupoNome"]=> "Peixes"
),
)
}
[1]=>
array(3) {
["groupoURL"]=> string(7) "executivo"
["grupoNome"]=> string(13) "Executivo"
["subgrupos"]=> array(
array(
["subgrupoURL"]=> "aves",
["subgrupoNome"]=> "Aves"
),
array(
["subgrupoURL"]=> "carnes",
["subgrupoNome"]=> "Carnes"
),
)
}
}
I still do not have a solution, but I'm trying to create something, but this would not be the ideal way:
$test = ...Recebe os resultados da consulta
$newArray = [];
foreach($test as $array) {
switch ($array["groupoURL"]) {
case "express":
$newArray["express"]["grupoNome"] = $array["grupoNome"];
$newArray["express"]["grupoURL"] = $array["groupoURL"];
$newArray["express"]["subgrupos"][] = ["subgrupoNome" => $array["subgrupoNome"], "subgrupoURL" => $array["subgrupoURL"]];
break;
case "executivo":
$newArray["executivo"]["grupoNome"] = $array["grupoNome"];
$newArray["executivo"]["grupoURL"] = $array["groupoURL"];
$newArray["executivo"]["subgrupos"][] = ["subgrupoNome" => $array["subgrupoNome"], "subgrupoURL" => $array["subgrupoURL"]];
break;
...
default:
break;
}
}
The solution above works, however I'm checking the "group" of each item. It may happen that the name of this group is changed, or a new group is entered.
Would anyone have any suggestions? Thank you for your attention.