php输出JSON多层嵌套的问题

財神
  • 8

`

$ch= '
    [{
        "school": "A校",
        "g": "一年级",
        "c": "一班",
        "n": [
            "男#25",
            "女#29"
        ]
    },
    {
        "school": "A校",
        "g": "一年级",
        "c": "二班",
        "n": [
            "男#30",
            "女#22"
        ]
    
    }]
    '

`

PHP循环输出:

<h1>学校</h1><h2>年级</h2><h3>班级</h3>
<div>
<ul>
<li><u>性别</u>:人数</li>
<li><u>性别</u>:人数</li>
<!--以上"li"循环输出-->
</ul>
</div>

代码

{
$chcd= json_decode($ch, true);

for($i=0;$i<count($chcd);$i++){
    echo "".$chcd[$i]['type']."<br /><h1>".$chcd[$i]['school']."&nbsp;&nbsp;".$chcd[$i]['c']."&nbsp;&nbsp;".$chcd[$i]['yy']."</h1>";
    
    echo $chcd->def[$i]->cx; 
    echo "<br /><br />";
}

不能循环输出“性别”和“人数”,请求指导!

评论
阅读 247
1 个回答
随便循环
$json = '[{
    "school": "A校",
    "g": "一年级",
    "c": "一班",
    "n": [
        "男#25",
        "女#29"
    ]
},
{
    "school": "A校",
    "g": "一年级",
    "c": "二班",
    "n": [
        "男#30",
        "女#22"
    ]

}]';
$arr = json_decode($json, true);
$html = '';
foreach ($arr as $v) {
    $html.="<h1>".$v['school']."</h1><h2>".$v['g']."</h2><h3>".$v['c']."</h3>";
    foreach ($v['n'] as $g) {
        $sex = explode('#', $g);
        $html.="<div><ul><li><u>".$sex[0]."</u>".$sex[1]."</li></div>";
    }    
}
echo $html;
撰写回答

登录后参与交流、获取后续更新提醒

宣传栏