Bonjour,
Je viens de finir d'écrire une méthode PHP, j'aimerai avoir des avis et des conseil afin de l'améliorer car j'ai l'impression que je me suis un peut compliqué la vie et qu'on peut faire plus simple.
Le but est de créer un tableau de sous catégorie indexé par les catégorie parente correspondant à partir de données récupérées via une requête. Je ne sais pas si c'est très clair mais voici le var_dump des données :
ARRAY (SIZE=24)
38 =>
OBJECT(SFKGROUP_CATEGORY)[28]
PUBLIC 'ID' => STRING '38' (LENGTH=2)
PUBLIC 'ID_SUPER_CATEGORY' => STRING '34' (LENGTH=2)
PUBLIC 'NAME' => STRING 'SPORT' (LENGTH=6)
PUBLIC 'SUPER_CATEGORY' => NULL
14 =>
OBJECT(SFKGROUP_CATEGORY)[29]
PUBLIC 'ID' => STRING '14' (LENGTH=2)
PUBLIC 'ID_SUPER_CATEGORY' => NULL
PUBLIC 'NAME' => STRING 'TENNIS' (LENGTH=10)
PUBLIC 'SUPER_CATEGORY' => NULL
16 =>
OBJECT(SFKGROUP_CATEGORY)[30]
PUBLIC 'ID' => STRING '16' (LENGTH=2)
PUBLIC 'ID_SUPER_CATEGORY' => NULL
PUBLIC 'NAME' => STRING 'CINEMA' (LENGTH=8)
PUBLIC 'SUPER_CATEGORY' => NULL
11 =>
OBJECT(SFKGROUP_CATEGORY)[31]
PUBLIC 'ID' => STRING '11' (LENGTH=2)
PUBLIC 'ID_SUPER_CATEGORY' => STRING '14' (LENGTH=2)
PUBLIC 'NAME' => STRING 'FILM' (LENGTH=7)
Avec ça je dois construire un tableau indexé de SPORT, l'index sport va contenir TENNIS idem pour le CINEMA.
Voici le code PHP (qui fonctionne très bien) :
<?php
public function buildMenu($categories)
{
$menuParent = [];
// Table created parent menus.
foreach ($categories as $k => $category) {
if (($category->id_super_category == 14) && ($category->id_super_category)) {
$categories[$k]->super_category = 'cinema';
}
else if (($category->id_super_category == 16) && ($category->id_super_category)) {
$categories[$k]->super_category = 'tennis';
}
if (
($category->id_super_category == 14) ||
($category->id_super_category == 16)
) {
$menuParent[$category->id] = ['category' => $category->name, 'super_category' => $category->super_category];
}
}
foreach ($categories as $k => $category) {
foreach ($menuParent as $name => $parent) {
if ($category->id_super_category == $name) {
$link = strUri($parent['super_category'] . '/' . $parent['category'] . '/' . $category->name);
$this->subMenu[$parent['category']][$parent['super_category']][] = [
'name' => $category->name,
'link' => $link,
'super_category' => $parent['super_category']
];
}
}
}
return $this->subMenu;
}
?>
Si vous pouvez m'aider à l'améliorer ou le simplifier ça serai cool ;)
Merci d'avance pour vos réponses