访问foreach

时间:2017-04-14 22:42:54

标签: php json

我正在尝试访问json请求的各个部分,典型的响应是:

{
   "Overview" : {
      "firstresultposition" : 1,
      "totalresultsreturned" : 2,
      "linkpop" : "2",
      "domainpop" : "2",
      "netpop" : "1",
      "ippop" : "1"
   },
   "Results" : [
      {
         "Links" : [
            {
               "UrlTo" : "http://www.eclecticaartisans.com/",
               "Anchor" : "Eclectica Artisans' Shop",
               "nofollow" : "0"
            }
         ],
         "IP" : "64.14.78.39",
         "Index" : 1,
         "DomainRank" : "5",
         "UrlFrom" : "http://www.shoppernews.com/directory.html"
      },
      {
         "UrlFrom" : "http://shoppernews.com/directory.html",
         "DomainRank" : "4",
         "Index" : 2,
         "IP" : "64.14.78.39",
         "Links" : [
            {
               "UrlTo" : "http://www.eclecticaartisans.com/",
               "Anchor" : "Eclectica Artisans' Shop",
               "nofollow" : "0"
            }
         ]
      }
   ]
}

我要做的是在1个foreach循环中获取2个数据而不是2个:

<?php
$returnSK = file_get_contents("REQUEST_URL");
$seoKicks = json_decode($returnSK, true);
print "<pre>"; print_r($returnSK); print "</pre>";
foreach ($seoKicks['Results'] as $key => $val2) {
    echo $val2['UrlFrom'];
    foreach ($val2['Links'] as $arr) {
        echo $arr['Anchor'];
    }
}
?>

上面的代码工作正常,但我真的需要使用1 foreach循环访问“UrlFrom”和“Anchor”值(如果可能的话,上面的2个foreach在添加到我的实时项目时稍微复杂一点)数据库)任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

有一个foreach,

foreach ($seoKicks['Results'] as $key => $val2) {
    echo $val2['UrlFrom'];
    echo $val2['Links'][0]['Anchor'];
}