2015-01-04 43 views
1

我有一个包含24个项目的php关联数组。我想穿过它们并打印4行,每行有6列。按设置打印php数组项目

这是如何实现的?

+0

Hi Wikki。只要快速浏览一下你的一些旧问题,你很幸运 - 尽管有很多这类简单的问题,但仍有一些赞扬,没有降价。所以你知道,我们真的很喜欢这个问题,当问题出现在先前的研究和努力的证据。这个问题至少会受益于包含关联数组的代码片段。其次,一些背景会有所帮助 - 下面的答案假设你在一个web过程中,但你可以使用控制台。更多细节=更好的答案! – halfer

回答

1

这应该为你工作:

(例如,我使用的数字数组,并添加键)

<?php 

    $array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24); 
    $count = 1; 

    foreach($array as $k => $v) { 

     echo sprintf(" Key: %3d Value %3d", $k, $v); 

     if($count % 6 == 0) 
      echo "<br />"; 

     $count++; 
    } 

?> 

输出:

Key: 0 Value 1 Key: 1 Value 2 Key: 2 Value 3 Key: 3 Value 4 Key: 4 Value 5 Key: 5 Value 6 
Key: 6 Value 7 Key: 7 Value 8 Key: 8 Value 9 Key: 9 Value 10 Key: 10 Value 11 Key: 11 Value 12 
Key: 12 Value 13 Key: 13 Value 14 Key: 14 Value 15 Key: 15 Value 16 Key: 16 Value 17 Key: 17 Value 18 
Key: 18 Value 19 Key: 19 Value 20 Key: 20 Value 21 Key: 21 Value 22 Key: 22 Value 23 Key: 23 Value 24 
0

像这样的东西应该做的技巧:

$columns = 6; 
$count = $columns; 
foreach ($array as $k=>$v) { 
    print $v.", "; 
    $count--; 
    if (!$count) { 
     print "<br/>"; 
     $count = $columns; 
    } 
}