将php多维数组输出到html列表 [英] Output php multidimensional array to html list

查看:264
本文介绍了将php多维数组输出到html列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php脚本中设置了以下数组,我正在尝试按照以下代码将其输出.我试过循环,但我不知如何显示子数组.我希望有人可以帮助我.

I have the following array set in a php script and i am trying to get it to output as per the code below. I have tried looping but i am at a loss as to how i get it to show the sub arrays. I am hoping someone can help me.

PHP阵列

$fruits = array();
$fruits[] = array('type' => 'Banana', 'code' => 'ban00');
$fruits[] = array('type' => 'Grape', 'code' => 'grp01');
$fruits[] = array('type' => 'Apple', 'code' => 'apl00',
               array('subtype' => 'Green', 'code' => 'apl00gr'),
               array('subtype' => 'Red', 'code' => 'apl00r')
            );
$fruits[] = array('type' => 'Lemon', 'code' => 'lem00');

所需的输出

<ul>
    <li><input type="checkbox" name="fruit" value="Banana"> Banana</li>
    <li><input type="checkbox" name="fruit" value="Grape"> Grape</li>
    <li>Apple
        <ul>
            <li><input type="checkbox" name="fruit" value="Green"> Green</li>
            <li><input type="checkbox" name="fruit" value="Red"> Red</li>
        </ul>
    </li>
    <li><input type="checkbox" name="fruit" value="Lemon"> Lemon</li>
</ul>

推荐答案

您可以使用递归函数.请注意,这只是一个示例,而不是直接的解决方案,因为我们在这里学习而不是完成工作-请根据需要进行更改.

You can use recursive function. Note that this is a example and not a direct solution, as we are here to learn and not to get the job done - change this as needed.

function renderList(array $data) {
   $html = '<ul>';
   foreach ($data as $item) {
      $html .= '<li>';
      foreach ($item as $key => $value) {
         if (is_array($value)) {
             $html .= renderList($value);
         } else {
             $html .= $value;
         }
      }
      $html .= '</li>';
   }
   $html .= '</ul>';
   return $html;
}

$data = array();
$data[] = array('A');
$data[] = array('B', array(array('C')));
$data[] = array('D');

echo renderList($data);

其输出为:

  • A
  • B
    • C
    • 或以html形式:

      <ul>
          <li>A</li>
          <li>B
              <ul>
                  <li>C</li>
              </ul>
          </li>
          <li>D</li>
      </ul>
      

      这篇关于将php多维数组输出到html列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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