带有逻辑参数的PHP多维数组(有些大脑扭曲)

Problem: I have a variables from magento that stored in the model class and can be get as

$productArray[] = array();
foreach ($order->getAllItems() as $item) {
    $productArray[] = array(
        "product"  => $item->getName(),
        "qty"   => $item->getQtyOrdered(),
        "amount" => $item->getPrice(),
    );
}

This are the values if print_r the $productArray[]:
Sample Output 1:

array(1) {
  [0]=>
  array(3) {
    ["product_name"]=>
    string(12) "Test Product"
    ["product_qty"]=>
    string(6) "2.0000"
    ["product_price"]=>
    string(7) "12.0000"
  }
}


Sample Output 2:

array(2) {
  [0]=>
  array(3) {
    ["product_name"]=>
    string(12) "Test Product"
    ["product_qty"]=>
    string(6) "2.0000"
    ["product_price"]=>
    string(7) "12.0000"
  }
  [1]=>
  array(3) {
    ["product_name"]=>
    string(6) "Test 2"
    ["product_qty"]=>
    string(6) "5.0000"
    ["product_price"]=>
    string(7) "22.0000"
  }
}

And how can you make it like this?(should be print like this)
If output 1: Final Output 1

<input type="hidden" name="product" value="Test Product" />
<input type="hidden" name="amount" value="24.00" />


If output 2: Final Output 2

<input type="hidden" name="product1" value="Test Product" />
<input type="hidden" name="amount1" value="24.00" />
<input type="hidden" name="product2" value="Test 2" />
<input type="hidden" name="amount2" value="110.00" />

The amount value will be get in product_price * product_qty.

Have some fun :) This is only a dummy problem, but this can be helpful to others

Like this:

<?php
foreach($productArray as $i => $product){
  $index = count($productArray) == 1 ? "" : $i; //So we don't have index when only 1 element
  $amount = $product['product_price'] * $product["product_qty"];
  $name = $product['product_name'];
?>
  <input type="hidden" name="product<?php echo $index; ?>" value="<?php echo $name;?>" />
  <input type="hidden" name="amount<?php echo $index;?>" value="<?php echo $amount;?>" />
<?php
}
?>

Hope this helps. Cheers

not sure about magento but in normal php it would be:

<?php
  $productArray = array(
    array(
      "product_name" => "Test Product",
      "product_qty" => "2.0000",
      "product_price" => "12.0000"
),
    array(
  "product_name"=> "Test 2",
      "product_qty"=>"5.0000",
      "product_price"=>"22.0000"
    )
  );

  foreach($productArray as $v) {
    echo '<input type="hidden" name="product" value="'.$v["product_name"].'" />';
    echo '<input type="hidden" name="amount" value="'.($v["product_qty"]*$v["product_price"]).'" />';
  }
?>

When making arrays of form fields in php, use "product[$id]" as the name, then php will regurgitate a neat array in $_POST. You can even do name="product[$id][price]" and you'll get a 2D array.

Note that if your webshop trusts hidden form data to haul around the cart during checkout (as you seem to do) you got a gaping security hole, so please post the web address, I'd like to order stuff for free !