Php 如何将此json字符串打印到列表?
我构建了一个从数据库表获取值的json。 现在我想在php中将下面的json打印到未排序的列表中。 如何将此打印到下面的json列表中 这是我的数组和预期输出Php 如何将此json字符串打印到列表?,php,json,Php,Json,我构建了一个从数据库表获取值的json。 现在我想在php中将下面的json打印到未排序的列表中。 如何将此打印到下面的json列表中 这是我的数组和预期输出 { "id": "6", "name": "aaaaa", "actove_from": "2000", "firstlevelrelations": { "1": { "name": "bbbbb", "active_from": "1990
{
"id": "6",
"name": "aaaaa",
"actove_from": "2000",
"firstlevelrelations": {
"1": {
"name": "bbbbb",
"active_from": "1990"
},
"5": {
"name": "cccccc",
"active_from": "2003"
},
"4": {
"name": "dddddd",
"active_from": "1992",
"2": {
"name": "fffff",
"active_from": "1990"
}
},
"7": {
"name": "ggggg",
"active_from": "2015"
},
"9": {
"name": "hhhhhh",
"active_from": "1990",
"10": {
"name": "yyyyy",
"active_from": "1997"
}
}
}
}
乌普图特:
<ul>
<li>aaaaaa</li>
<li>2000</li>
<ul>
<li>bbbbbb</li>
<li>1990</li>
<li>ccccc</li>
<li>2003</li>
<li>dddddd</li>
<li>1992
<ul>
<li>fffff</li>
<li>1990</li>
</ul>
</li>
<li>gggggg</li>
<li>2015</li>
<li>hhhhhh</li>
<li>1990
<ul>
<li>yyyyyy</li>
<li>1997</li>
</ul>
</li>
</ul>
</ul>
- AAAAA
- 2000年
- bbbbbb
- 1990年
- ccccc
- 2003年
- dddddd
- 一九九二年
- fffff
- 1990年
- gggggg
- 2015年
- 嗯嗯
- 1990年
- yyyyyy
- 1997年
在这里,您可以访问原始数据,现在可以在DOM元素标记之间打印它们。我并没有为您解决所有问题,但这应该可以帮助您实现目标
$array = json_decode($json, true);
foreach($array as $key => $value)
{
if(is_array($value))
{
//start building your sublist
}else{
//start building your list
}
}
//将字符串解码为assoc数组
$json=json_decode($your_json_string_,true);
功能菜单($arr){
$result=“”;
foreach($arr as$key=>$item){
//如果项目为数组,则调用菜单函数
$result.=“”(是数组($item)?菜单($item):$item.“ ”;
}
返回“”$result.
”;
}
回声菜单($json);
这将创建所需的输出(但没有缩进)获取JSON编码的字符串并将其转换为PHP关联数组。现在循环数组并输出HTML。循环数组时,我想在一次循环执行中打印两个列表(li),而不是逐个打印。像这样依赖固定数组索引名似乎很危险,除非您确定它永远不会更改。在他的问题中,它似乎总是具有相同的索引。
foreach($jsonvar as $key=>$value){
//if it is just a simple value
$valuesInsideYourJson = $value;
//if it is an array of other objects.
if(is_array($valuesInsideYourJson)){
foreach($valuesInsideYourJson as $val){
// this in inside the firstlevelrelation
// do whatever you want
}
}
}
$array = json_decode($json, true);
foreach($array as $key => $value)
{
if(is_array($value))
{
//start building your sublist
}else{
//start building your list
}
}
// decode the string as assoc array
$json = json_decode($your_json_string_here, true);
function menu( $arr ) {
$result = "";
foreach( $arr as $key => $item ) {
// if the item is array calls the menu function
$result .= "<li>" . (is_array($item) ? menu($item) : $item)."</li>";
}
return "<ul>" . $result . "</ul>";
}
echo menu($json);