我有一个名为articles.json的json文件,这些是内容:
{
"articles": [
{
"id": 1,
"title": "a"
}
]
}
这是我解码它的文件:
<?php
include "inc/header.inc.php";
$file = file_get_contents("articles.json");
$arts = json_decode($file, true);
?>
<div class="container">
<h1>Articles</h1>
</div>
<div class="grey">
<div class="container">
<?php
foreach($arts as $article) {
print_r($article);
echo "<div class='part'>";
echo "<div class='part-header'>".$article['title']."</div>";
echo "</div>";
}
?>
</div>
</div>
<?php
include "inc/footer.inc.php";
?>
我收到以下错误:Notice: Undefined index: title in /vagrant/www/ComputingEssentials/articles.php on line 19
答案 0 :(得分:3)
其中还有另一个维度。其内部索引为零:
echo "<div class='part-header'>".$article[0]['title']."</div>";
或者,如果您期望多篇文章,请更改索引来源:
foreach($arts['articles'] as $article) {
echo "<div class='part'>";
echo "<div class='part-header'>".$article['title']."</div>";
echo "</div>";
}
答案 1 :(得分:0)
将$arts = json_decode($file, true);
更改为$arts = json_decode($file)->articles;
并访问您的标题:$article->title
如果你有充分的理由继续使用数据作为关联数组,请使用:
$jsonData = json_decode($file, true);
$arts = $jsonData['articles'];
然后,您可以像这样访问标题:$article['title']