Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

php输出JSON多层嵌套的问题

`

$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 />";
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
随便循环
$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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...