问题描述:

I'm pretty new to PHP and am looking into using array_chunk() to split an array into three parts to display it as a three column list. Let's say I have an array like this

 $input_array = array('a', 'b', 'c', 'd', 'e', 'f');

$chunks = array_chunk($input_array, 3, true));

and I want to output something like:

<div class="left">

<ul>

<li>a</li>

<li>b</li>

</ul>

</div>

<div class="middle">

<ul>

<li>c</li>

<li>d</li>

</ul>

</div>

<div class="right">

<ul>

<li>e</li>

<li>f</li>

</ul>

</div>

I've seen some really helpful examples on here but none that show how to foreach loop each chunk of the original array to place where you need within your html/css.

Is this a job for array_slice? But what if my array is dynamically populated and I don't know how big it will be at a given time?

Thanks!

网友答案:
$div_class = array("left","middle","right"); 
$input_array = array('a', 'b', 'c', 'd', 'e', 'f');
$chunks = array_chunk($input_array, 2);

foreach($chunks as $i => $mychunk)
{
    echo "<div class=\"$div_class[$i]\">";
    echo "<ul>";

    foreach($mychunk as $newchunk) 
    {
    echo "<li>";
    echo $newchunk;
    echo "</li>";
    }

    echo "</ul>";
    echo "</div>";
}

Output -

<div class="left">
<ul>
<li>a</li>
<li>b</li>
</ul>
</div>
<div class="middle">
<ul>
<li>c</li>
<li>d</li>
</ul>
</div>
<div class="right">
<ul>
<li>e</li>
<li>f</li>
</ul>
</div>
网友答案:

Your array_chunk($input_array, 3, true)) code returns the chunk with three values but according to your output that you expected you have to set array_chunk($input_array, 2, true)

to follow the link to know more about array_chunk()

$input_array = array('a', 'b', 'c', 'd', 'e', 'f');
$chunks = array_chunk($input_array, 2, true);

//print_r($chunks);
for( $i=0;$i<count($chunks);$i++ ){
   echo "<div>\n";
   echo "<ul>\n";
   foreach( $chunks[$i] as $k=>$v ){

     echo "<li>$v</li>\n";

   }
  echo "</ul>\n";
  echo "</div>\n\n";
 }

to see the output check the following link http://codepad.org/8K1luela

相关阅读:
Top