简体   繁体   English

PHP 数组 foreach 项

[英]PHP array foreach item

I'm Having issues grabbing values in a multi level array.我在获取多级数组中的值时遇到问题。

This is my JSON I am grabbing with CURL and putting into a variable.这是我用 CURL 抓取并放入变量的 JSON。

{
  "id": 454626,
  "results": [
    {
      "iso_3166_1": "SK",
      "release_dates": [
        {
          "certification": "U",
          "iso_639_1": "sk",
          "note": "",
          "release_date": "2020-02-20T00:00:00.000Z",
          "type": 3
        }
      ]
    },
    {
      "iso_3166_1": "DE",
      "release_dates": [
        {
          "certification": "6",
          "iso_639_1": "",
          "note": "",
          "release_date": "2020-02-13T00:00:00.000Z",
          "type": 3
        }
      ]
    },
    {
      "iso_3166_1": "TW",
      "release_dates": [
        {
          "certification": "G",
          "iso_639_1": "",
          "note": "",
          "release_date": "2020-02-21T00:00:00.000Z",
          "type": 3
        }
      ]
    }
  ]
}

This is my PHP code that I'm having issues with.这是我遇到问题的 PHP 代码。

$id_tmdb = $row[id_tmdb];

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.themoviedb.org/3/movie/$id_tmdb/release_dates?api_key=API-KEY",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET"
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$result = json_decode($response, true);


foreach($result[results][release_dates] as $key=>$val){
    echo "$val[release_date]";
}

I'm trying to get the release_date but it just shows blank.我正在尝试获取release_date但它只是显示为空白。

I have another page that is formatted the same way so I am unsure why it isn't working.... Thank you for all your help.我有另一个页面的格式相同,所以我不确定为什么它不起作用......谢谢你的帮助。

Your $result['results'] value is also an array and you need to iterate over that as well as the release_dates array:你的$result['results']值也是一个数组,你需要迭代它以及release_dates数组:

foreach($result['results'] as $results) {
    foreach ($results['release_dates'] as $val){
        echo "$val[release_date]\n";
    }
}

Output (for the sample JSON provided):输出(对于提供的示例 JSON):

2020-02-20T00:00:00.000Z
2020-02-13T00:00:00.000Z
2020-02-21T00:00:00.000Z

Demo on 3v4l.org 3v4l.org 上的演示

This should get you there:这应该让你到达那里:

foreach($result['results'] as $res){
    echo $res['release_dates'][0]['release_date']."\n";
}

3v4l link 3v4l链接

On a side-note, I put the array keys in quotes to prevent php warnings.在旁注中,我将数组键放在引号中以防止 php 警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM