将我的JSON字符串格式化为< ol> PHP中的有序列表 [英] Format my JSON string into an <ol> ordered list in PHP
问题描述
我正在为一个宠物项目开发一个简单的CMS。我现在有一个JSON字符串,它包含一个菜单结构的页面ID和父页面ID的列表。
I'm working on a simple CMS for a pet project. I currently have a JSON string that contains a list of page ID's and Parent page ID's for a menu structure.
现在我想将此字符串转换为嵌套或分层列表(有序列表)。
I want to now convert this string into a nested or hierarchical list (ordered list).
我试过寻找循环,但似乎已经结束了一个过于复杂的子类范围。我努力在PHP中找到合适的轻量级解决方案。
I've tried looking looping through but seem to have ended up with an overly complex range of sub classes. I'm struggling to find a suitable light-weight solution in PHP.
以下是JSON:
Here's the JSON:
**[{"id":3,"children":[{"id":4,"children":[{"id":5}]}]},{"id":6},{"id":2},{"id":4}]**
以下是所需的输出:
Here's the desired output:
<ol>
<li>3
<ol>
<li>4</li>
<ol>
<li>5</li>
</ol>
</ol>
</li>
<li>6</li>
<li>2</li>
<li>4</li>
</ol>
是否有内置于PHP的内容可以简化此过程?有没有人有过这方面的经验?
Is there anything built in to PHP that can simplify this process? Has anyone had any experience of this before?
我是PHP和SE的新手。期待您的回音。
I'm a newbie to PHP and SE. Looking forward to hearing from you.
这是我目前的进度(效果不理想)
<ol>
<?php
$json = '[{"id":3,"children":[{"id":4,"children":[{"id":5}]}]},{"id":6},{"id":2},{"id":4}]';
$decoded = json_decode($json);
$pages = $decoded;
foreach($pages as $page){
$subpages = $decoded->children;
echo "<li>".$page->id."</li>";
foreach($subpages as $subpage){
echo "<li>".$subpage->id."</li>";
}
}
?>
</ol>
推荐答案
您可以使用递归深入数据。如果当前值是一个数组,则再次递归。考虑这个例子:
You can use recursion to get deep inside the data. If the current value is an array then recursion again. Consider this example:
$json_string = '[{"id":3,"children":[{"id":4,"children":[{"id":5}]}]},{"id":6},{"id":2},{"id":4}]';
$array = json_decode($json_string, true);
function build_list($array) {
$list = '<ol>';
foreach($array as $key => $value) {
foreach($value as $key => $index) {
if(is_array($index)) {
$list .= build_list($index);
} else {
$list .= "<li>$index</li>";
}
}
}
$list .= '</ol>';
return $list;
}
echo build_list($array);
这篇关于将我的JSON字符串格式化为< ol> PHP中的有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!