Backend Development
PHP Tutorial
How to count quantities by product category in PHP shopping cart and use it for shipping calculations
How to count quantities by product category in PHP shopping cart and use it for shipping calculations

This article introduces how to read the shopping cart array from the PHP Session and aggregate the number of products according to the numerical classification in the database (such as category=1, 2, 3), which is suitable for business scenarios such as freight rate calculation and other business scenarios.
In the PHP simple shopping cart implemented based on Session, $_SESSION["cart_item"] is usually an associative array with product code (code) as the key, and each element contains fields such as name, code, category, quantity, etc. To achieve "counting the total number of items by category", the key is not to reconstruct the entire shopping cart structure, but to dynamically classify and accumulate when traversing the cart array - this is the effective idea verified by the original author "step back and use a simple method".
Here is a clear, robust, and straightforwardly integrable implementation:
✅ Step 1: Initialize classification counter (recommended to use associative array)
//Initialize the empty array to ensure that all target categories have a default value of 0 $categoryCounts = [1 => 0, 2 => 0, 3 => 0]; // Supplement based on actual category ID, or obtain dynamically: array_fill_keys($validCategories, 0) // If the classification range is unknown, it can be safely initialized to an empty array (automatically filled in later) $categoryCounts = [];
✅ Step 2: Traverse the shopping cart, press category to accumulate quantity
if (!empty($_SESSION["cart_item"])) {
foreach ($_SESSION["cart_item"] as $item) {
$cat = (int)$item["category"]; // Force conversion to integer to avoid logical errors caused by string keys if (!isset($categoryCounts[$cat])) {
$categoryCounts[$cat] = 0;
}
$categoryCounts[$cat] = (int)$item["quantity"];
}
}
// Output example: total number of items in each category foreach ($categoryCounts as $catId => $totalQty) {
echo "Category {$catId}: {$totalQty} items<br>";
}
✅ Step 3: Combine freight logic (example)
$shipping = 0;
if (!empty($categoryCounts)) {
if (isset($categoryCounts[1]) && $categoryCounts[1] > 0) {
$shipping = 5.00; // Category 1 items are subject to an additional $5 shipping fee}
if (isset($categoryCounts[2]) && $categoryCounts[2] >= 3) {
$shipping = 8.00; // Category 2, up to 3 pieces, $8 bulk shipping}
// Other rules...
}
echo "Estimated shipping: $" . number_format($shipping, 2);
⚠️ Notes and best practices
- Always check the data type : $item["category"] and $item["quantity"] may be strings, and must be explicitly converted (int) to avoid the implicit splicing error of '1' '2' === '12';
- Avoid relying on a fixed category list : In a production environment, it is recommended to first check the database to obtain a valid category (such as SELECT DISTINCT category FROM products), and then initialize $categoryCounts;
- Session security : ensure that session_start() has been called and the shopping cart data has been basically filtered before writing (such as htmlspecialchars() is only used for output, not storage);
- Performance tip : The time complexity of this aggregation operation is O(n), which is completely stress-free for hundreds of items. If high-frequency statistics are required in the future, consider caching the summary results to $_SESSION["cart_summary"] to avoid repeated calculations.
Through this lightweight and highly readable method, you can quickly obtain accurate quantity statistics by category dimensions without changing the existing shopping cart addition and deletion logic, providing a reliable data basis for freight strategies, inventory warnings, or report analysis.
The above is the detailed content of How to count quantities by product category in PHP shopping cart and use it for shipping calculations. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20606
7
13699
4
How to implement Eloquent Attribute Accounting in PHP_Laravel data operation audit tracking [Tutorial]
Apr 14, 2026 am 06:45 AM
Adding logs directly to Eloquent's $casts or getFooAttribute is invalid because the accessor/mutator is only triggered when the model attributes are read and written, and cannot capture batch updates, native SQL and other changes that bypass the model. The audit needs to cover all data modification scenarios.
How to safely modify table names referenced by foreign keys in Laravel migrations
Apr 17, 2026 pm 01:22 PM
This article introduces how to safely update the target table name of an existing foreign key constraint (such as changing from seller to sellers) through migration in Laravel, covering the key steps and precautions for deleting old constraints and rebuilding new constraints.
NGINX URL redirection in action: detailed explanation and best practices
Apr 22, 2026 am 06:17 AM
This article aims to provide a professional tutorial on how to configure URL redirection using Nginx. We will focus on the use of the rewrite directive, especially how to redirect the root path to a URL with query parameters, and delve into the difference between the redirect (302 temporary redirect) and permanent (301 permanent redirect) flags and their considerations in SEO and browser caching to ensure that the Nginx configuration is both efficient and in line with best practices.
MySQL inventory entry and exit details and balance query (filtered by date and warehouse)
Apr 17, 2026 pm 01:34 PM
This article explains in detail how to use MySQL CTE and UNION ALL to build a dynamic inventory flow report, summarize the purchase (Purchase), outbound (Order) quantity and real-time balance of each commodity according to the specified date and warehouse ID, and output a structured result set that can be directly used for business dashboards.
How to implement lazy loading of images to improve long page performance
Apr 22, 2026 am 04:26 AM
This article introduces how to use the loading="lazy" attribute of native HTML to easily load images on demand in the viewport, significantly reducing initial page resource consumption. It is especially suitable for scrolling long pages such as portfolios and galleries containing a large number of images. No JavaScript framework required and compatible with modern mainstream browsers.
How to safely transcribe .PO files to Cyrillic and avoid NUL character pollution
Apr 17, 2026 pm 12:44 PM
This article explains in detail the root cause of NUL NUL NUL (null byte) garbled characters when processing .po localized files in PHP, and provides a repair solution based on safe file stream operations. It emphasizes avoiding direct reading and writing of the same file, and recommends using a professional PO parsing library instead of manual string replacement.
Correctly loading related models in Laravel: Use with() to preload users and their posts
Apr 28, 2026 am 06:10 AM
In Laravel, if you need to get a specified user based on ID and preload its associated posts at the same time, you must put with() before findOrFail(); otherwise, findOrFail() will immediately execute the query and return a single model, and subsequent with() and first() will fail or produce unexpected results.
How to safely output the string 'null' instead of an empty value in PHP
Apr 28, 2026 am 06:39 AM
In PHP 8, when the variable value is null, echo directly will output empty content; this article introduces a variety of safe and concise methods (such as the null coalescing operator, ternary abbreviation, etc.) to make the null value explicitly displayed as the string "null".





