使用foreach在数组内部使用Echo数组?

时间:2017-06-27 08:38:48

标签: php arrays foreach

我想访问,这个数组

  

(结果中的release_dates内的认证)

  "results": [
   {
     "iso_3166_1": "IN",
     "release_dates": [
     {
        "certification": "U",
        "note": "",
     }
     ]
   }
   ]

我正在使用此代码:

 if (isset($response4["results"]) && is_array($response4["results"])) 
 {
     foreach ($response4["results"] as $genreObject) 
     {
         $release_dates_iso_3166_1 = $genreObject["iso_3166_1"];
         $release_dates_certification = $genreObject["release_dates"]["certification"];
         $stmt->execute();
      } 
  } 

但此代码只能访问iso_3166_!而不是certification

  

错误:注意:未定义索引:认证

2 个答案:

答案 0 :(得分:2)

因为if (isset($response4["results"]) && is_array($response4["results"])) { foreach ($response4["results"] as $genreObject) { $release_dates_iso_3166_1 = $genreObject["iso_3166_1"]; $release_dates_certification = $genreObject["release_dates"][0]["certification"]; $stmt->execute(); } } 是数组,您必须使用此数组的第一个元素:

<html><head><meta charset="utf-8"><title>Blog</title><link rel="stylesheet" href="styles.css"></head><body><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"/><script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"/><script  src="main2.js"/><div class="container">  <form id="contact" action="" method="post"><h3>Colorlib Contact Form</h3><h4>Contact us for custom quote</h4><fieldset><input id="name" placeholder="Name" type="text" tabindex="1" ></fieldset><fieldset><input id="author" placeholder="Author" type="text" tabindex="2" ></fieldset><fieldset><textarea id="content" placeholder="Content...." tabindex="5" /></fieldset><fieldset>    <button id="nextButton"> Next </button>  </fieldset><p class="copyright">Designed by <a href="https://colorlib.com" target="_blank" title="Colorlib">Colorlib</a></p></form></div>    </body></html>

答案 1 :(得分:1)

release_dates键包含数组,而不是对象。所以你应该迭代或访问密钥。

if (isset($response4["results"]) && is_array($response4["results"])) {
    foreach ($response4["results"] as $genreObject) {
       $release_dates_iso_3166_1 = $genreObject["iso_3166_1"];
       $release_dates_certification = null;
       foreach ($genreObject["release_dates"] as $release_dates_elements) {
           $release_dates_certification = $release_dates_elements["certification"];
       }
    }
}