Php 将JSON转换为HTML表
对于我来说,将json文件转换为html输出的最佳方式是什么 我有一个输出一些json的脚本。我的json看起来像:Php 将JSON转换为HTML表,php,Php,对于我来说,将json文件转换为html输出的最佳方式是什么 我有一个输出一些json的脚本。我的json看起来像: [ { "description" : "desc 1 test", "image" : "Http://test.com/gram.png", "money" : null, "title" : "title2" }, { "description" : "desc 2 test", "image" : "http://test.com/
[ { "description" : "desc 1 test",
"image" : "Http://test.com/gram.png",
"money" : null,
"title" : "title2"
},
{ "description" : "desc 2 test",
"image" : "http://test.com/daddy.gif",
"money" : "$7",
"title" : "title2"
},
{ "description" : "desc 3 test",
"image" : "test.com/41057.png",
"money" : null,
"title" : "title3"
}
]
我想让它说出下面这样的东西(测试数据),但请注意这些类是奇数和偶数的-我不知道我将如何进行
<tr class="gradeA">
<td>title1</td>
<td class="center">image1</td>
<td class="center">desc1</td>
<td class="center">money1</td>
</tr>
<tr class="gradeA">
<td>title2</td>
<td class="center">image2</td>
<td class="center">desc2</td>
<td class="center">money2</td>
</tr>
<tr class="gradeA">
<td>title3</td>
<td class="center">image3</td>
<td class="center">desc3</td>
<td class="center">money3</td>
</tr>
<tr class="gradeA">
<td>title4</td>
<td class="center">image4</td>
<td class="center">desc4</td>
<td class="center">money4</td>
</tr>
标题1
图1
描述1
货币1
标题2
图2
描述2
金钱2
标题3
图3
描述3
金钱3
标题4
图4
描述4
金钱4
这应该行得通
$str = "json code";
$arr = @json_decode($str)[0];
$html = "<table>";
$even = true;
forach ( $arr as $value ) {
$html .= "<tr class = '" . ( $even ? 'even' : 'odd' ) . "'>";
$html .= "<td>{$value['title']}</td>";
$html .= "<td>{$value['image']}</td>";
$html .= "<td>{$value['description']}</td>";
$html .= "<td>{$value['money']}</td>";
$html .= "</tr>";
$even = !$even;
}
$html .= "</table>";
$str=“json-code”;
$arr=@json_decode($str)[0];
$html=“”;
$偶数=真;
forach($arr作为$value){
$html.=”;
$html.=“{$value['title']}”;
$html.=“{$value['image']}”;
$html.=“{$value['description']}”;
$html.=“{$value['money']}”;
$html.=”;
$even=!$even;
}
$html.=”;
但是您在示例中提供的类不是奇偶的?您可以使用$res=json\u decode($json)
要将其解码到php数组,请快速搜索该词(可能在搜索词中添加CSS
),您将发现比您需要的更多。您可以使用CSS伪选择器。gradeA:odd
和。gradeA:偶数
,而不是在php中执行此操作。谢谢,事实上,我不知道“斑马条纹”这个名字通常php不喜欢访问数组json_decode($str)[0]中的方法;您可以在不使用@字符的情况下在两行中完成,但它将是相同的,就像$arr=json_decode($str)$arr=isset($arr[0])$arr[0]:数组();您的json不正确,或者删除第二行的[0]。尝试打印($arr);若要查看foreach之后的第一行内容,请尝试新的一行