【发布时间】:2019-01-08 01:57:33
【问题描述】:
我正在学习使用 foreach 语句循环遍历 json 文件的教程。当然,在示例中,我遵循这个工作正常,但我似乎无法让它在我的版本上工作。我认为该错误表明我实际上并没有传递数组。这是否意味着问题出在 json 文件中?还是有语法问题?
警告:在第 27 行的 C:\xampp\htdocs\loops\json_example.php 中为 foreach() 提供的参数无效
JSON 文件:movies.json
{ //json object
"movies": [ //movies = array
{
"title": "The Godfather",
"year": "1972",
"genre": "Drama",
"director": "Francis Ford Copolla"
},
{
"title": "Superbad",
"year": "2007",
"genre": "Comedy",
"director": "Greg Mottola"
},
{
"title": "The Departed",
"year": "2006",
"genre": "Drama",
"director": "Martin Scorsese"
},
{
"title": "Saving Private Ryan",
"year": "1998",
"genre": "Action",
"director": "Steven Spielberg"
},
{
"title": "The Expendables",
"year": "2010",
"genre": "Action",
"director": "Sylvester Stallone"
}
]
}
PHP 代码:json_example.php
<?php
$jsondata = file_get_contents("movies.json"); #set variable, function "file_get_contents" grabs everything in the file. can also use with a website is url is within () to insert entire site.
$json = json_decode($jsondata, true); #decodes json so that we can parse it
?>
<!DOCTYPE html>
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<div id="container">
<h1>My Favorite Movies</h1>
<ul>
<?php
foreach($json['movies'] as $key => $value) {
echo '<h4>'.$value['title'].'</h4>';
echo '<li>Year: '.$value['year'].'</li>';
echo '<li>Genre: '.$value['genre'].'</li>';
echo '<li>Director: '.$value['director'].'</li>';
}
?>
</ul>
</div>
</body>
</html>
请原谅我的评论,我还在学习。
【问题讨论】:
-
它是一个对象,而不是一个数组。像
$json->movies一样访问它。另外,学会print_r()或var_dump()PHP变量,这样你就不会瞎了。 -
@MonkeyZeus 他使用 true 作为第二个参数,所以这个强制关联数组
-
希望 JSON 中没有这些 cmets?
-
当然要去掉json文件中的cmets。
-
删除 json 中可以正常工作的 cmets。 json_decode 失败