2012-09-29 91 views
4

可能重复:
php - How do I print this multidimensional array?如何打印多维数组在PHP

我有以下格式的数组

Array ([0] => Array ([product_id] => 33 [amount] => 1) [1] => Array ([product_id] => 34 [amount] => 3) [2] => Array ([product_id] => 10 [amount] => 1))

我想从这个数组获取输出如下格式

 
Product ID Amount 
33    1 
34    3 
10    1 

任何人都可以请帮我解决这个问题。 var_dump的变量是。

 
array 
    0 => 
    array 
     'product_id' => string '33' (length=2) 
     'amount' => string '1' (length=1) 
    1 => 
    array 
     'product_id' => string '34' (length=2) 
     'amount' => string '3' (length=1) 
    2 => 
    array 
     'product_id' => string '10' (length=2) 
     'amount' => string '1' (length=1) 

+0

基本[的foreach()](http://php.net/manual/en/control-structures.foreach.php)环 – 2012-09-29 10:19:57

+0

给我试过代码 –

+0

这里有2000米的答案HTTP:// stackoverflow.com/search?q=%5Bphp%5D+multidimensional,我相信他们中的一个会有所帮助。 – vascowhite

回答

4

我相信这是你的阵列

$array = Array ( 
     0 => Array ("product_id" => 33 , "amount" => 1) , 
     1 => Array ("product_id" => 34 , "amount" => 3) , 
     2 => Array ("product_id" => 10 , "amount" => 1)); 

使用foreach

echo "<pre>"; 
echo "Product ID\tAmount"; 
foreach ($array as $var) { 
    echo "\n", $var['product_id'], "\t\t", $var['amount']; 
} 

使用array_map

echo "<pre>" ; 
echo "Product ID\tAmount"; 
array_map(function ($var) { 
    echo "\n", $var['product_id'], "\t\t", $var['amount']; 
}, $array); 

输出

Product ID Amount 
33   1 
34   3 
10   1 
+0

不客气@Damith – Baba

1

试试这个..

foreach($arr as $a) 
{ 
    echo $a['product_id']; 
    echo $a['amount']; 
} 

格式,按您的需求量的。

2
 <table> 
     <tr> 
      <th>Product Id</th> 
      <th>Ammount</th> 
     </tr> 

     <?php 
     foreach ($yourArray as $subAray) 
     { 
      ?> 
      <tr> 
       <td><?php echo $subAray['product_id']; ?></td> 
       <td><?php echo $subAray['amount']; ?></td> 
      </tr> 
      <?php 
     } 
     ?> 
    </table> 
+0

非常感谢你,这也很有效。 – Damith