访问array_chunk每块 [英] Accessing each chunk of array_chunk

查看:92
本文介绍了访问array_chunk每块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty新PHP和期待到使用的 array_chunk()分裂阵列分为三部分,以显示它作为一个三列的列表。比方说,我有一个这样的数组

  $ input_array =阵列('A','B','C','D','E','F');
 $块= array_chunk($ input_array,3,真实));

和我想的输出是这样的:

 < D​​IV CLASS =左>
 < UL>
  <李>一种< /李>
  <立GT; B< /李>
 < / UL>
 < / DIV>< D​​IV CLASS =中间>
 < UL>
  <立GT; C< /李>
  <李> D< /李>
 < / UL>
 < / DIV>< D​​IV CLASS =右>
 < UL>
  <立GT; E< /李>
  <立GT; F< /李>
 < / UL>
< / DIV>

我见过一些放在这里真正有用的范例但没有说明如何到foreach循环原数组的每个块的地方,你需要你的HTML / CSS之内。

这是对array_slice工作?但是,如果我的数组动态填充,我不知道这将是在给定时间有多大?

谢谢!


解决方案

  $ div_class =阵列(左,中,右);
$ input_array =阵列('A','B','C','D','E','F');
$块= array_chunk($ input_array,2);的foreach($块为$ I => $ mychunk)
{
    回声< D​​IV CLASS = \\$ div_class [$ i] \\>中;
    回声< UL>中;    的foreach($ mychunk为newchunk $)
    {
    回声<立gt;中;
    回声$ newchunk;
    回声< /李>中;
    }    回声< / UL>中;
    回声< / DIV>中;
}

输出 -

 < D​​IV CLASS =左>
< UL>
<李>一种< /李>
<立GT; B< /李>
< / UL>
< / DIV>
< D​​IV CLASS =中间>
< UL>
<立GT; C< /李>
<李> D< /李>
< / UL>
< / DIV>
< D​​IV CLASS =右>
< UL>
<立GT; E< /李>
<立GT; F< /李>
< / UL>
< / DIV>

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>

这篇关于访问array_chunk每块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆