【发布时间】:2021-12-24 13:28:12
【问题描述】:
我正在用 PHP 解码 JSON。我想显示第一个类别,然后是相关文章链接,然后是标题。这是我正在尝试的 PHP 代码 + Json..
<html>
<head>
</head>
<body>
<?php
$json = '[{
"article": "https://example.com",
"category": "Cat2",
"title" : "1the title Cat2"
}, {
"article": "https://example.com",
"category": "Cat1",
"title" : "1the title Cat1"
}, {
"article": "https://example.com",
"category": "Cat1",
"title" : "2the title Cat1"
}, {
"article": "https://example.com",
"category": "Cat2",
"title" : "2the title Cat2"
}, {
"article": "https://example.com",
"category": "Cat1",
"title" : "3the title Cat1"
}]';
$values = json_decode($json, true);
$res = [];
foreach ($values as $entry) {
$category = $entry['category'];
if (! array_key_exists($category, $res)) {
$res[$category] = [];
}
$res[$category][] = $entry;
}
foreach($res as $category => $entry): ?>
<h1><?= $category; ?></h1>
<?php foreach($entry as $article): ?>
<p><?= $entry['title']; ?></p>
<?php endforeach; ?>
<?php endforeach;
?>
</body>
</html>
它有时会返回数组,现在什么都没有......
我想要这样的东西......
<h1>Cat2</h1>
<p>https://example.com</p>
<span>the title</span>
<p>https://example.com</p>
<span>the title</span>
<h1>Cat1</h1>
<p>https://example.com</p>
<span>the title</span>
<p>https://example.com</p>
<span>the title</span>
<p>https://example.com</p>
<span>the title</span>
提前致谢。
【问题讨论】:
-
$entry['title']应该是$article['article'] -
“未定义的索引:标题”应该给你一个提示。
-
@NigelRen 你是对的..
-
@NigelRen 我可以在没有第二次 foreach 的情况下获得这些键值吗?