为什么只有一个PHP脚本工作,而另一个给出了一个错误,只循环数组的最后一项?



我试图创建一个简单的太来获得使用API的各种坐标对的WalkScores。我有两个不同的UI。一个有两个输入文本区域,一个用于lats,一个用于lons。它工作得很好,但这对用户来说是更多的工作。第二个UI在文本区域的每一行上都有每个坐标对。下面的第一个脚本可以工作,而第二个脚本即使使用相同的函数也会出现错误。

脚本工作。它从表单中获取两个字段,并创建要在循环中使用的数组。

<?
$apiKey = 'a55fc4524343bfc9cdd901361092197c';
//comes from form
$lat = $_POST['lat'];
$lon = $_POST['lon'];
// for testing without UI
// $lat = "41.767679,41.346483";
// $lon = "-72.680463,-73.251384";
// for testing without UI
$lats = explode(',', $lat);
$lons = explode(',', $lon);
$address = 'unknown';
for ($i = 0; $i < count($lats); $i++) {
$json = getWalkScore($lats[$i], $lons[$i], $address);
$json_walkScore = json_decode($json);
echo $lats[$i] . "rn";
echo $lons[$i] . "rn";
echo $json_walkScore->walkscore . "rn";
echo $json_walkScore->description . "rn";
}
function getWalkScore($lat, $lon, $address)
{
$address = urlencode($address);
$url = "http://api.walkscore.com/score?format=json&address=$address&lat=$lat&lon=$lon&wsapikey=a55fc4524343bfc9cdd901361092197c";
$str = @file_get_contents($url);
return $str;
}

不工作这看起来创建相同的数组在循环中使用,但返回一个错误">注意:试图获得属性'walkscore'的非对象在…"并且只返回最后一次迭代的预期输出。一双就够了。如果我使用硬编码数组,它工作得很好。

<?
$apiKey = 'c93ad8c6751f03a31889414b680eec49';
//Data sent from Ajax
$input = $_POST['input'];
//Split string based on new line from text area. Each item is on its own line.
$arr = explode("n", $input);
//Two arrays to hold data
$lats = [];
$lons = [];
//Break each pair into lat lng and push to arrays
foreach ($arr as $k => $v) {
$coord = explode(",", $v);
$lat = $coord[0];
$lon = $coord[1];
array_push($lats, $lat);
array_push($lons, $lon);
}
//using these hardcoded arrays it works fine.
// $lats = ["41.113676","41.104206"];
// $lons = ["-73.439233","-73.404587"];
//using these hardcoded arrays it works fine.

//Set address to unknown since it is not provided / needed
$address = 'unknown';
//loop over the number of lats, run the get walk score function to return the json data for output
for ($i = 0; $i < count($lats); $i++) {
$json = getWalkScore($lats[$i], $lons[$i], $address);
$json_walkScore = json_decode($json);
// print_r($json_walkScore);
echo $lats[$i] . "rn";
echo $lons[$i] . "rn";
echo $json_walkScore->walkscore . "rn";
echo $json_walkScore->description . "rn";
}
function getWalkScore($lat, $lon, $address)
{
$address = urlencode($address);
$url = "http://api.walkscore.com/score?format=json&address=$address&lat=$lat&lon=$lon&wsapikey=a55fc4524343bfc9cdd901361092197c";
$str = @file_get_contents($url);
return $str;
}

关于为什么第一个是工作,而第二个不是的想法吗?如果有问题请告诉我。谢谢!

经过更多的测试,这一行

$arr = explode("n", $input);

需要改成

$arr = explode("rn", $input);

有趣……相同的EXACT输出,但如果代码决定这次工作。

相关内容

最新更新