如何用PHP array_push构建WooCommerce重构购物车的理想数组
First, let's clarify the structure you're aiming for: a nested associative array where top-level keys are product_ids, and each maps to another associative array with size as keys and quantity as values. That looks like this:
$cart = [ 86253 => [ 35 => 1, 36 => 1, 38 => 2, // ... more size/quantity pairs ], 86245 => [ 36 => 7, 39 => 4, // ... more size/quantity pairs ] ];
While array_push() works great for adding elements to indexed arrays, it's not the most intuitive tool for building this kind of associative nested structure. Direct key assignment will get you exactly the format you want, so let's modify your existing code to build this array:
Modified Code
// Initialize empty cart array $cart = []; foreach($items as $item => $values) { $_product = wc_get_product( $values['data']->get_id()); if($_product->post_type == 'product_variation'){ // Extract the values we need $product_id = $_product->parent_id; $size = $values['variation']['taille']; $quantity = $values['quantity']; // If this product ID isn't in the cart yet, create an empty sub-array for it if(!isset($cart[$product_id])){ $cart[$product_id] = []; } // Assign size as the key and quantity as the value in the product's sub-array $cart[$product_id][$size] = $quantity; } }
If You Must Use array_push()
If you specifically need to use array_push() (even though it's not the best fit for your desired associative structure), you can adjust the code to store each size/quantity pair as a sub-array. Note this will change the structure slightly (using indexed arrays instead of size-as-key):
$cart = []; foreach($items as $item => $values) { $_product = wc_get_product( $values['data']->get_id()); if($_product->post_type == 'product_variation'){ $product_id = $_product->parent_id; $size = $values['variation']['taille']; $quantity = $values['quantity']; if(!isset($cart[$product_id])){ $cart[$product_id] = []; } // Use array_push to add a size/quantity pair as an associative sub-array array_push($cart[$product_id], [ 'size' => $size, 'quantity' => $quantity ]); } }
This will produce a cart array formatted like:
$cart = [ 86253 => [ ['size' => 35, 'quantity' => 1], ['size' => 36, 'quantity' => 1], // ... more pairs ], // ... other products ];
But again, the first approach is the perfect match for the structure you described.
内容的提问来源于stack exchange,提问作者Thomas Baudry

