2010-05-12 101 views
1

我有这个多维数组,我想要打印到一个表中,每个记录/项目进入它自己的行,但它列明智。这是我得到的输出:http://mypetshopping.com/product.php打印多维数组

ps:$ product的值将根据正在查看的产品进行动态调整。

<?php 
session_start(); 
?> 
<table> 
<thead> 
<tr> 
<th>Name</th> 
<th>Hash</th> 
<th>Quantity</th> 
<th>Size</th> 
<th>Color</th> 
</tr> 
</thead> 
<tbody> 

<?php 


    function addCart($product, $quantity, $size,$color) { 

    $hash = md5($product); 

    $_SESSION['cart'][$product]['name'] = $product; 
    $_SESSION['cart'][$product]['hash'] = $hash; 
    $_SESSION['cart'][$product]['quantity'] = $quantity; 
    $_SESSION['cart'][$product]['size'] = $size; 
    $_SESSION['cart'][$product]['color'] = $color; 

    } 

    addCart('Red Dress',1,'XL','red'); 
    addCart('Blue Dress',1,'XL','blue'); 
    addCart('Slippers',1,'XL','orange'); 
    addCart('Green Hat',1,'XXXL','green'); 

    $cart = $_SESSION['cart']; 

    foreach($cart as $product => $array) { 

    foreach($array as $key => $value) { 

    ?> 

    <tr> 
    <td><?=$value;?></td> 
    <td><?=$value;?></td> 
    <td><?=$value;?></td> 
    <td><?=$value;?></td> 
    <td><?=$value;?></td> 
    </tr> 


    <?php 


    } 

    } 


    ?> 

回答

1

我觉得你的循环代码应该这样写:

<?php foreach($cart as $product => $array) { ?> 
<tr> 
    <?php foreach($array as $key => $value) { ?> 
    <td><?php echo $value; ?></td> 
    <?php } ?> 
</tr> 
<?php } ?> 
0

尝试改变你的代码:

foreach($cart as $product => $array) { ?> 
<tr> 
<?php 
    foreach($array as $key => $value) { 
?>  
     <td><?=$value;?></td> 

<?php 


    } 

?> 
    </tr> 

<?php 

} 
0
<?php 
echo "<ul>"; 
for ($layer = 0; $layer < 3; $layer++) 
{ 
    echo "<li>The layer number $layer"; 
    echo "<ul>"; 

    for ($row = 0; $row < 3; $row++) 
    { 
     echo "<li>The row number $row"; 
     echo "<ul>"; 

     for ($col = 0; $col < 3; $col++) 
     { 
      echo "<li>".$shop[$layer][$row][$col]."</li>"; 
     } 
     echo "</ul>"; 
     echo "</li>"; 
    } 
    echo "</ul>"; 
    echo "</li>"; 
} 
echo "</ul>"; 
?> 

http://www.webcheatsheet.com/php/multidimensional_arrays.php