[英]how to access multidimensional array at different level in php
I am unable to access title and description in php. 我无法在php中访问标题和描述。 Though I have slight clue that we will have to use foreach loop at different level but being a beginner I have no idea how to fetch key and values in foreach loop. 尽管我有一点线索,我们将不得不在不同级别使用foreach循环,但是作为一个初学者,我不知道如何在foreach循环中获取键和值。
Please run the following lines in .php and see the result. 请在.php中运行以下行,然后查看结果。
<?php
$url = "https://newsapi.org/v2/top-headlines?sources=google-news&apiKey=SECRET_KEY";
$response = json_decode(file_get_contents($url), true);
echo "<pre>";
print_r($response);
foreach ($response as $key => $value) {
}
?>
Yes you are right you can access the values using foreach. 是的,您是对的,您可以使用foreach访问值。 Just change $response
to $response['articles']
because all data is present in the articles array of $response variable. 只需将$response
更改$response
$response['articles']
因为所有数据都存在于$ response变量的articles数组中。 You can iterate through articles array using foreach as below to access each element. 您可以使用下面的foreach遍历Articles数组来访问每个元素。
foreach ($response['articles'] as $key => $value) {
echo $value['title']; // to access title
echo $value['description']; // to access description
}
thank you for your timely response, I tried this way and it worked. 感谢您的及时答复,我尝试了这种方法,它确实有效。
foreach ($response['articles'] as $key => $articles)
{
echo $articles['source']['id'];
echo "<br>";
echo $articles['description'];
echo "<br>";
echo $articles['author'];
echo "<br>";
echo "Published at"."<br>".$articles['publishedAt'];
echo "<br><br><br><br>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.