PHP 7.2(Debian9+Apache2.4)二维数组遍历输出及计数求助
Hey there! Let's figure out why your foreach loop isn't working and how to count your products properly.
First, let's clarify your array structure: it looks like $result['allproduct'] contains two types of entries—product main data (with integer keys like 1, 2) and their corresponding 12-month sales data (with keys like 1.1, 2.2). Your earlier foreach probably failed because it didn't distinguish between these two types, leading to errors when trying to access product-specific keys on sales data.
Here's a working solution tailored to your setup:
// First, confirm your array structure (you can uncomment to debug) // var_dump($result['allproduct']); // Extract the product list array $productsCollection = $result['allproduct']; $totalProductCount = 0; // Traverse the array, filtering out product main data foreach ($productsCollection as $key => $item) { // Only process entries with integer-like keys (product main data) if (ctype_digit($key)) { $totalProductCount++; // Output product basic info echo "<h3>Product #$key</h3>"; echo "<ul>"; echo "<li>商品名称: " . htmlspecialchars($item['product']) . "</li>"; echo "<li>库存数量: " . $item['quantity'] . "</li>"; echo "<li>价格: " . htmlspecialchars($item['price']) . "</li>"; echo "</ul>"; // Fetch corresponding 12-month sales data (match key pattern: "number.number") $salesDataKey = "$key.$key"; if (isset($productsCollection[$salesDataKey])) { echo "<h4>12个月销售明细</h4>"; echo "<ul>"; foreach ($productsCollection[$salesDataKey] as $month => $salesQty) { echo "<li>$month: $salesQty 件</li>"; } echo "</ul>"; } echo "<hr>"; } } // Output total product count echo "<p>总产品数量: $totalProductCount</p>";
Key points to note:
- Filtering product data: We use
ctype_digit($key)to target only product main entries, avoiding errors from trying to accessproduct/quantitykeys on sales data arrays. - Matching sales data: The
$salesDataKey = "$key.$key"line matches your stated key pattern (e.g.,1→1.1,2→2.2). If your actual key pattern is different (like1→1.1for all), adjust this line to fit. - Safe output:
htmlspecialchars()is used to escape user-generated content, preventing potential XSS vulnerabilities—always a good practice for web outputs. - Counting products:
$totalProductCountincrements each time we process a valid product entry, giving you the total number of products.
If your original loop failed, it's almost certainly because you tried to process every entry in $result['allproduct'] without filtering, leading to undefined index errors when accessing product keys on sales data.
内容的提问来源于stack exchange,提问作者jhon

