如何在Php中解析JSON并循环数据

如何在Php中解析JSON并循环数据,php,arrays,json,web,Php,Arrays,Json,Web,嘿 我想知道我正在使用一个API,该API以JSON格式向我提供新闻。现在,我正在制作一个网站,将所有这些新闻。我无法解析此JSON数据,这是包含此数据的URL。 我的Php代码将这些数据解码成一个数组,然后,我无法将对象和数组分开。我知道我有多少结果,我可以简单地通过它循环,但我需要知道如何获得这些数据 <?php $json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&api

我想知道我正在使用一个API,该API以JSON格式向我提供新闻。现在,我正在制作一个网站,将所有这些新闻。我无法解析此JSON数据,这是包含此数据的URL。

我的Php代码将这些数据解码成一个数组,然后,我无法将对象和数组分开。我知道我有多少结果,我可以简单地通过它循环,但我需要知道如何获得这些数据

    <?php
$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');


print_r( json_decode($json, true));
$jsons= ( json_decode($json, true));
echo $jsons[0]["article"];



?>


$jsons
不是数组,而是对象。您想要的是
$jsons->articles[0]

您的PHP代码是错误的,
echo$jsons[0][“article”]-这是行不通的。
您需要将其替换为
print\r($jsons[“articles”][0])。因此,我认为您所说的JSON数据是指如何将其推出或遍历数据

由于已将assoc参数设置为true,因此将返回一个数组

首先是对代码的更正,希望能帮助您理解json和json是如何工作的

在本例中,我们将推出所有文章

$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');
$news = json_decode($json, true);

foreach ($news["articles"] as $i => $article) {
    echo '<h2>' . $article['title'] . '</h2>';
    echo '<img src="' . $article['urlToImage'] . '"/>';
    echo '<p>Published on ' . $article['publishedAt'] . '</p>';
    echo '<p>' . $article['description'] . '</p>';
    echo '<a href="' . $article['url'] . '">Read more</a>';
}
$json=file\u get\u contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');
$news=json_decode($json,true);
foreach($news[“articles”]作为$i=>$article){
回音“.$article['title']”;
回声';
echo“发表在“$article['publishedAt']”上。

; 回显“”.$article[“description]”。

; 回声'; }

您可能还想在w3schools.com上看到它。

这是一个数组,因为他已将assoc参数设置为true,我忘记了该部分。应该是
$jsons['articles'][0]
。顺便说一句,谢谢你的否决票。很棒的工作真有魅力。好的,再帮我一点,例如,我想得到$json['totalResults'],但这似乎不起作用。用
$json
替换
$json
,就像这样
$json['totalResults']
。您可能希望将变量
$jsons
重命名为
$news
,以便于理解。
json\u decode()
获取一个json编码的字符串并将其转换为PHP变量。在你的例子中是一个PHP数组。是的,兄弟,这就是问题所在,谢谢你帮了我。快速提问为什么这里的每个人都如此粗鲁,以至于我一发布任何东西,他们就简单地投了反对票。我个人认为你的问题不清楚,但我们掌握了窍门。我认为说你可以通过阅读(通过研究)学到一切太容易了。我还认为你的问题对于有经验的代码来说是无用的。所以我不会投你的反对票,我也不同意社区规则,因为每个人都应该有空间,就像7年前一样:)。所以我不能给你一个明确的理由,为什么你会投反对票,因为我对社区规则不再感兴趣;)
$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');

print_r( json_decode($json, true));
$jsons= ( json_decode($json, true));
print_r( $jsons["articles"][0] );
echo $jsons["articles"][0]['title'];
$json = file_get_contents('https://newsapi.org/v2/top-headlines?country=us&apiKey=5d0d49e595dc4b64a2fd3916b617ad8c');
$news = json_decode($json, true);

foreach ($news["articles"] as $i => $article) {
    echo '<h2>' . $article['title'] . '</h2>';
    echo '<img src="' . $article['urlToImage'] . '"/>';
    echo '<p>Published on ' . $article['publishedAt'] . '</p>';
    echo '<p>' . $article['description'] . '</p>';
    echo '<a href="' . $article['url'] . '">Read more</a>';
}