我从此链接Click Here
中提取了以下JSON我想要做的是在PHP中编写一个函数,它将最近的目标邮政编码返回到源地址。所以它应该返回94536。
已经花了大约4个小时,而且这里的格式运气不好:)。 Ty提前。
这是我目前在代码点火器功能
中所拥有的<?php
已定义('BASEPATH')或退出('不允许直接访问脚本');
类位置扩展MX_Controller {
public function index()
{
$json = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=89706&destinations=94536|73301|61462&key=AIzaSyBQu1UgozO7yjQzYtvZkB05RI-5E6Qo5DU');
$jsondecoded = json_decode($json);
//testing to get first zip code just to make sure we can get zip code only (Not needed here)
$matches = [];
preg_match("#.*?(\d+)#", json_decode($json, true)['destination_addresses'][0], $matches);
echo $matches[1];
// just a test to see that the complete json is there. (Not needed here just for testing)
echo '<hr>';
echo '<pre>';
print_r($jsondecoded);
echo '</pre>';
echo '<hr>';
// looping though elements tryign to order the distance text by closest first (lost here but still testing)
foreach ($jsondecoded->rows as $element) {
echo '<pre>';
print_r($element);
echo '</pre>';
echo '<hr>';
}
// I need to build a function that find the closest destination_addresses zip code and return it. So i would need to sort the rows->elements->distance->text / value by the closest adn then match that to correct destination_addresses
}
}
答案 0 :(得分:1)
你只需要解码json让我们说它将在$ json变量中并使用简单的正则表达式,其中\d
代表数字
$json = ''; //your json from curl or any other way
$matches = [];
preg_match("#.*?(\d+)#", json_decode($json, true)['destination_addresses'][0], $matches);
echo $matches[1]; // your adress
如果json响应包含数组键等,可能需要添加一些检查。