PHP 使用 foreach 遍历 JSON

PHP Traverse through JSON using foreach

我一直在按照本指南使用两个不同的 API 创建一个应用程序,但该指南是旧的,因此其中一个 API 无法像指南中那样工作。我正在尝试从 google 地理编码 API 获取坐标并将它们粘贴到 Places for Web 中。我是 PHP 的新手,所以我按照指南的示例来遍历 JSON 对象,但整晚都在努力让它工作。 这是来自地点搜索 API

的 JSON 对象
{  
"html_attributions":[  ],
"results":[  
  {  
     "geometry":{  },
     "icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
     "id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
     "name":"Guadalajara Mexican Grill & Cantina",
     "opening_hours":{  },
     "photos":[  
        {  
           "height":2952,
           "html_attributions":[  ],
           "photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
           "width":5248
        }
     ],
     "place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
     "price_level":2,
     "rating":4.4,
     "reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
     "scope":"GOOGLE",
     "types":[  ],
     "vicinity":"105 North Main Street, Lake Elsinore"
  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  },
  {  }
],
"status":"OK"
}

我可能正在尝试将所有照片引用抓取到一个数组中?然后将它们插入 google 的 Place Photos API。这是我的尝试:

更新

<?php 
if(!empty($_GET["location"])){
    //$API_key = "";
    $maps_url = 'https://' .
    'maps.googleapis.com/' .
    'maps/api/geocode/json' .
    '?address=' . urlencode($_GET['location']) .
    '&key=';



    $maps_json = file_get_contents($maps_url);
    $maps_array = json_decode($maps_json, true);

    $lat = $maps_array['results'][0]['geometry']['location']['lat'];
    $lng = $maps_array['results'][0]['geometry']['location']['lng'];

    $places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
    'location=$lat,$lng' .
    '&radius=1500' .
    '&rankby=distance' .
    '&key=';

    $places_json = file_get_contents($places_url);
    $places_array = json_decode($places_json, true);

    if (!empty($places_array)) {
    foreach ($places_array as $item) {
        var_dump($places_array );
    }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <title>What is Here?</title>
  </head>
  <body>
 <h1>Type in a location</h1>
 <p>This program will display pictures of places to go in that area</p>

  <form action ="">
  <input type ="text" name ="location"/>
  <button type ="submit">Go!</button>
  </form>
  <br/>
  <?php
    echo "$lat $lng";
  ?>

似乎无法让 foreach 循环执行任何操作

$lat,$lng 变量或 API 调用是您的第一个问题,foreach 循环是第二个问题。

json_decode($someJSON, true); 从您的 json 创建一个关联数组,因此您不能使用 -> 箭头,它们是针对对象的。 More about this。 没有$item->photo_reference,使用:

$results = $places_array["results"];

foreach ($results as $item) {
    echo $item["photos"]["photo_reference"];
}

无效的请求意味着错误的url或错误的参数 如果 $lat 和 $lng 是变量,那么插值将无法使用单引号尝试使用这样的双引号 "location=$lat,$lng"

$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';

你应该删除半径或距离你不能在文档中同时获得它们 https://developers.google.com/places/web-service/search?hl=en-419

这是我在本地主机上运行的修改代码,请注意 $contextOptions 你不应该将它复制到你的代码中这是使 file_get_contents 在我的机器上运行的解决方法

之后 foreach 应该很简单,因为只是一个数组看看代码

 $thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
        'maps.googleapis.com/' .
        'maps/api/geocode/json' .
        '?address=' . urlencode($thelocation) .
        '&key=' . $thekey;

$contextOptions = array(
 "ssl" => array(
 "verify_peer"      => false,
 "verify_peer_name" => false,
 ),
);

$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);

$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];

$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
        "location=$lat,$lng" .
        '&rankby=distance' .
        '&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);

if (!empty($places_array)) {


 foreach ($places_array["results"] as $item) {

        echo $item["name"]."<br>";

    }
}

这打印....简单

AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group