遍历PHP多维数组时显示错误产品,附数组生成代码求助
First, let’s break down the likely issue with your current code. From the snippet you shared, it looks like you’re creating a separate array entry ($this_order_data) for every row returned by your recordset. But if a single order has multiple products, this approach will create standalone entries for each product instead of grouping them under their parent order ID. That’s almost certainly why your traversal is showing products incorrectly—you’re not organizing the data into a hierarchical structure that reflects orders and their associated products.
Fix: Group Products by Order ID
Here’s how to adjust your code to build a properly structured multidimensional array where each order contains all its products:
// Initialize an empty array to hold grouped orders $orders_data = []; while (!$combined->EOF) { $orders_id = $combined->fields['orders_id']; $customers_name = $combined->fields['customers_name']; $products_name = $combined->fields['products_name']; $products_model = $combined->fields['products_model']; $products_quantity = $combined->fields['products_quantity']; // Create a parent entry for the order if it doesn't exist yet if (!isset($orders_data[$orders_id])) { $orders_data[$orders_id] = [ 'orders_id' => $orders_id, 'customers_name' => $customers_name, 'products' => [] // Empty array to store this order's products ]; } // Add the current product to the order's product list $orders_data[$orders_id]['products'][] = [ 'name' => $products_name, 'model' => $products_model, 'quantity' => $products_quantity // Include any other product fields you need here ]; // Move to the next record in your result set $combined->MoveNext(); }
How to Traverse the Corrected Array
Now when you loop through the array, you can first iterate over each order, then loop through its products—this will display products correctly per order:
foreach ($orders_data as $order) { echo "<h3>Order #{$order['orders_id']} - {$order['customers_name']}</h3>"; echo "<ul>"; foreach ($order['products'] as $product) { echo "<li>{$product['quantity']}x {$product['name']} (Model: {$product['model']})</li>"; } echo "</ul>"; }
Additional Checks to Rule Out Other Issues
If grouping doesn’t fix the problem, here are a few more things to verify:
- Query Order: Make sure your SQL query is sorted by
orders_idfirst. If rows are mixed across orders, the grouping logic won’t work as intended. AddORDER BY orders_idto your SELECT statement. - Duplicate IDs: Check if your recordset has unexpected duplicate
orders_idvalues that might be causing overwrites in the array. - Field Name Typos: Double-check that all field names (
products_name,products_model, etc.) match exactly what’s returned by your query—small typos here would lead to missing or incorrect data.
Let me know if you still run into issues after trying these steps!
内容的提问来源于stack exchange,提问作者Steph3071

