【发布时间】:2019-02-19 11:33:18
【问题描述】:
我想按“类别”下的 ID 对我的 JSON 数据进行分类。现在我可以手动更改我想在 if 语句中显示的内容,但我希望它由实际用户完成。
我希望能够只显示类别->id = 1/2/3 的 JSON 数据。有没有一种方法可以通过按钮仅选择“一般”或“清理”博客文章?
<?php
$json_file = file_get_contents('posts.json', true);
$json = json_decode($json_file);
$posts = $json->posts;
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Blog</title>
</head>
<body>
<?php
foreach ($posts as $post) {
if($post->categories[0]->id == "1"){
?>
<div>
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->date; ?></p>
<p><?php echo $post->content; ?></p>
<p><?php echo $post->categories[0]->slug; ?></p>
</div>
<?php
}}
?>
</body>
</html>
这是 JSON 数据
{
"posts": [
{
"title": "My Lovely Blog",
"date": "22nd September 2018",
"content": "Hey guys so this is my brand new blog that I will be posting on weekly! Stay tuned for more :)",
"categories": [
{
"id": 1,
"slug": "general"
}
]
},
{
"title": "How to clean your home fast: 10 spring cleaning tips",
"date": "29th September 2018",
"content": "Declutter your home: There is a simple rule you can use to declutter you home. If you have not used something...",
"categories": [
{
"id": 2,
"slug": "cleaning"
}
]
},
{
"title": "7 Fashion Trends to Be Thankful for This Year",
"date": "24th November 2018",
"content": "The trickle down effect of this trend might take a while, but on the runways, office-appropriate clothing got a serious makeover. Blazers were paired with embellished short shorts at Prada and loose, 90s-inspired trousers at Tom Ford. At Celine, daywear was rendered in sherbet colors while Michael Kors topped off plunging tops and sarong sequin skirts with wide-cut blazers and flip flops. Just because you have gone corporate does not mean you cannot have fun.",
"categories": [
{
"id":3,
"slug":"fashion"
}
]
}
] }
感谢您的帮助!!!
【问题讨论】: