如何从foreach循环获取数组索引

时间:2015-03-03 10:41:12

标签: php arrays

如何从foreach循环获取数组索引,我使用session打印这样的购物车数据,我需要在表格中的代码列之前打印1,2,3,4等索引

<?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"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></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 个答案:

答案 0 :(得分:1)

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"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span></td>';     
        echo '</tr>';
        $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
        $total = ($total + $subtotal);
    }

使用箭头操作符,您可以在foreach循环中选择索引。