How to get array index from foreach loop
本问题已经有最佳答案,请猛点这里访问。
如何从foreach循环中获取数组索引,我使用session来打印cart数据,我需要在表中的code列之前打印1、2、3、4这样的索引。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php if(isset($_SESSION["products"])) { $total = 0; echo '<tbody>'; foreach ($_SESSION["products"] as $cart_itm) { echo '<tr>'; echo '<td>?</td>'; echo '<td>'.$cart_itm["code"].'</td>'; echo '<td>'.$cart_itm["name"].'</td>'; echo '<td>'.$cart_itm["qty"].'</td>'; echo '<td><input type="text" name="product_qty_desired" class="spinner" value="1" size="3" /></td>'; echo '<td>'.$currency.$cart_itm["price"].'</td>'; echo '<td class="subtotal">Subtotal : </td>'; echo '<td><span class="remove-itm">×</span></td>'; echo '</tr>'; $subtotal = ($cart_itm["price"]*$cart_itm["qty"]); $total = ($total + $subtotal); } echo '<tr>'; echo '<td></td>'; echo '<td></td>'; echo '<td>Total QTY :</td>'; echo '<td></td>'; echo '<td>?</td>'; echo '<td>Total</td>'; echo '<td>'.$currency.$total.'</td>'; echo '<td></td>'; echo '</tr>'; echo '</tbody>'; }else{ echo 'Your Cart is empty'; } ?> |
http://i62.tinypic.com/2qaifrt.png
谢谢
热烈地
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | foreach ($_SESSION["products"] as $index => $cart_itm) { echo '<tr>'; echo '<td>' . $index . '</td>'; echo '<td>'.$cart_itm["code"].'</td>'; echo '<td>'.$cart_itm["name"].'</td>'; echo '<td>'.$cart_itm["qty"].'</td>'; echo '<td><input type="text" name="product_qty_desired" class="spinner" value="1" size="3" /></td>'; echo '<td>'.$currency.$cart_itm["price"].'</td>'; echo '<td class="subtotal">Subtotal : </td>'; echo '<td><span class="remove-itm">×</span></td>'; echo '</tr>'; $subtotal = ($cart_itm["price"]*$cart_itm["qty"]); $total = ($total + $subtotal); } |
使用箭头运算符,可以在foreach循环中选择索引。