简体   繁体   English

使用foreach通过JSON遍历PHP

[英]PHP Traverse through JSON using foreach

I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. 我一直按照本指南使用两个不同的API创建应用程序,但该指南过时了,因此其中一个API不能像本指南中那样工作。 I am trying to grab coordinates from google geocoding API and stick them into Places for Web. 我正在尝试从Google地理编码API中获取坐标并将其粘贴到Web地方。 I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work. 我是PHP的新手,所以我按照指南的示例遍历JSON对象,但整夜都在努力使其工作。 Here is the JSON object from the place search API 这是地点搜索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"
}

I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. 我正在尝试将所有照片引用都捕获到数组中?,然后将它们插入Google的Place Photos API中。 Here is my attempt at that: 这是我的尝试:

UPDATE UPDATE

<?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";
  ?>

Just can't seem to get the foreach loop to do anything 只是似乎无法让foreach循环执行任何操作

The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second. $lat,$lng变量或API调用是您的第一个问题,而foreach循环是第二个问题。

The json_decode($someJSON, true); json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. 从您的json创建一个关联数组,因此您不能使用->箭头,这些箭头用于对象。 More about this . 更多关于这个 There's no $item->photo_reference , use: 没有$item->photo_reference ,使用:

$results = $places_array["results"];

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

the invalid request means wrong url or bad parameters if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this "location=$lat,$lng" 如果$ lat和$ lng是变量,则无效请求意味着错误的url或错误的参数,然后插值将无法使用单引号尝试使用双引号,例如“ location = $ lat,$ lng”

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

you should remove radius or distance you cant get both its on the docs https://developers.google.com/places/web-service/search?hl=en-419 您应该在文档https://developers.google.com/places/web-service/search?hl=zh-419上删除不能同时获得的半径或距离

here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine 这是我在localhost上运行的修改后的代码,请注意$ contextOptions,不应将其复制到代码上,这是使file_get_contents在我的计算机上工作的解决方法

after that the foreach should be easy since is only an array look at the code 之后,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>";

    }
}

this prints....easy 这印...。容易

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

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

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