将php多维数组输出到html列表(Output php multidimensional array to html list)

约定不等于承诺〃 2023-09-24 08:16 216阅读 0赞

  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 Array

  $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’);

  Desired Output

  • Banana
  • Grape
  • Apple

    • Green
    • Red
  • Lemon

  盾畳圭宛

  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=’

  • ‘;

      foreach ($data as $item) {

      $html .=’

  • ‘;

      foreach ($item as $key=> $value) {

      if (is_array($value)) {

      $html .=renderList($value);

      } else {

      $html .=$value;

      }

      }

      $html .=’

  • ‘;

      }

      $html .=’

‘;

  return $html;

  }

  $data=array();

  $data[]=array(‘A’);

  $data[]=array(‘B’, array(array(‘C’)));

  $data[]=array(‘D’);

  echo renderList($data);

  The output of this will be: ABCD

  Or in html form:

  • A
  • B

    • C
  • D

发表评论

表情:
评论列表 (有 0 条评论,216人围观)

还没有评论,来说两句吧...

相关阅读

    相关 php输出数组函数

      php数组的定义与数组遍历,php数组函数的用法与例子,php数组取值赋值,php多维数组的循环输出等,供大家学习参考。   1、php数组定义和遍历   2、php数

    相关 html输出php数组

      php中输出关联型数组的方式有很多,下面我就来说说比较常用的输出方式:   第一个当然要属foreach:   foreach在java中也是经常拿来用的,它是专门设计