如何在foreach中显示标题和副标题 - PHP

时间:2011-07-03 12:13:33

标签: php foreach

我有以下数组格式:

Array
(
    [0] => Array
       (
            [title] => Main Cat
            [subfield] => Array
              (
                [1] => Array
                    (                            
                        [sub_title] => Sub Cat 1
                    )

                [2] => Array
                    (                            
                        [sub_title] => Sub cat 2
                    )

               )
         )
       [1] => Array
        (
            [title] => Main cat 2
            [subfield] => Array
              (
                [1] => Array
                    (                            
                        [sub_title] => Test Cat 1                            
                    )

                [2] => Array
                    (                            
                        [sub_title] => Test Cat 2
                    )

               )
         )

我需要使用PHP使用foreach以下列格式显示它。 的 O / P:

Main Cat

 Sub Cat 1

 Sub Cat 2

Main cat 2

 Test Cat 1

 Test Cat 2

如何做到这一点......提前致谢...

编辑:我的尝试

 $f = 1;
      foreach($vars['fields'] as $value) {
         $vars['topic_main'][] = $value['title']."<br>&nbsp;".$value['subfield'][$f]['sub_title']."<br>";
         $f++;
      }

      $vars['title'] = implode(' ' ,$vars['topic_main']);

我的O / P

Main Cat

 Sub Cat 1 


Main cat 2

 Test Cat 1

3 个答案:

答案 0 :(得分:5)

假设您的阵列被称为类别。 (编辑:$ vars ['fields'])

foreach($vars['fields'] as $cat){

    echo $cat['title'].'<br/>';
    foreach($cat['subfield'] as $sub){
        echo $sub['subtitle'].'<br/>';
    }
}

答案 1 :(得分:1)

echo '<ul>';
foreach ($array as $item):
    echo '<li>';
    echo $item['title'];
    echo '<ul>';
    foreach ($item['subfield'] as $sub):
        echo '<li>';
        echo $sub['subtitle'];
        echo '</li>';
    endforeach;
    echo '</ul>';
    echo '</li>';
endforeach;
echo '</ul>';

答案 2 :(得分:0)

只为内部使用a和另一个foreach,问题是什么?

foreach ($arr as $main)
{  
  echo $main['title'];
  foreach ($main['subfield'] as $sub)
  {
     echo $sub['sub_title'];
   }

做一些化妆品......