Comment afficher correctement les éléments enfants dans l'élément parent
Je construis un système de boutique en ligne architecture MVC. J'ai la table MERCHANTS et la table PRODUCTS et CART . Un commerçant (magasin) peut avoir un ou plusieurs produits, chaque produit du système appartient à un magasin donc je veux afficher les produits par magasin quand je vais sur la page panier, je veux dire qu'une fois qu'un utilisateur ajoute par exemple des produits qui appartiennent à la même boutique, le panier doit afficher les produits comme une arborescence. J'ai déjà posté ce problème, j'ai pu réfléchir et venir avec la mise à jour de ce que j'ai fait, mais il n'affiche toujours pas correctement l'arborescence, comme lorsqu'un magasin a plus d'un produit dans le panier. Voici une illustration. Quelqu'un peut-il m'aider s'il vous plaît ou me dire ce que je fais mal
Model
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
$userId = 1; // This is just for an example
$itemsInCart= getCart($userId); // Fetch the items in cart from the DB on session
function getCart($userId): array
{
try {
$db = createConnection();
$sql = 'SELECT * FROM cart
LEFT JOIN products p ON cart.product_id = p.product_id
LEFT JOIN merchants m ON p.merchant_id = m.merchant_id
WHERE user_id = :userId ';
$stmt = $db->prepare($sql);
$stmt->bindValue(':userId', $userId, PDO::PARAM_INT);
$stmt->execute();
$invInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $invInfo;
} catch (PDOException $e) {
return [];
}
} |
Vue
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
$userCartDisplay = buildUserCartDisplay($itemsInCart); // Builds the cart elements' view
function buildUserCartDisplay($itemsInCart)
{
// Here's how you track if you need the header
$lastMerchantID = -1 ;
$html = '';
// Now loop
foreach($itemsInCart as $row)
{ $html .= '<div>';
// Only show merchant header on condition
if ($lastMerchantID <> $row['merchant_id']) {
$html .= '<ul>';
$html .= "". $row['merchant_name']."";
// Note that you've shows this header so you don't show it again.
$lastMerchantID = $row['merchant_id'];
$html .= '</ul>';
}
// Now output the rest
$html .= '<li>';
$html .= "".$row['product_model']."";
$html .= '</li>';
$html .= '</div>';
}
return $html;
}
echo $userCartDisplay; // Display the view |
Je veux afficher les produits par boutique de cette sorte ci-dessous
Code:
1 2 3 4 5 6 7 8
| <ul>MERCHANT_NAME
<li>Product model</li>
</ul>
<ul>MERCHANT_NAME
<li>Product model</li>
<li>Product model</li>
<li>Product model</li>
</ul> |
Mais malheureusement voila ce qui resort
Code:
1 2 3 4 5 6 7 8 9 10 11 12
| <ul>MERCHANT_NAME
<li>Product model</li>
</ul>
<ul>MERCHANT_NAME
<li>Product model</li>
</ul>
<ul>
<li>Product model</li>
</ul>
<ul>
<li>Product model</li>
</ul> |