【问题标题】:Find the shortest distance Destination Address找到最短距离的目的地地址
【发布时间】:2016-06-09 09:58:22
【问题描述】:

我从该链接Click Here 中提取了以下 JSON

我想做的是用 PHP 编写一个函数,将最近的目的地邮政编码返回到原始地址。所以它应该返回 94536。

在这里玩了大约 4 个小时,但对这里的格式不太满意 :)。提前泰。

这是迄今为止我在代码点火器函数中所拥有的

<?php

defined('BASEPATH') OR exit('不允许直接脚本访问');

类位置扩展 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

}

}

【问题讨论】:

  • 您的问题出在哪一部分?如我所见,您需要解码json,在elements 中找到最小距离的id,然后在destination_addresses 的元素中通过正则表达式找到具有相同id 的邮政编码

标签: php json codeigniter


【解决方案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 响应包含数组键等,您可能需要添加一些检查。

Working fiddle

【讨论】:

  • 我喜欢 preg_match 很高兴看到工作,但它只是呼应了第一个目标地址。我需要计算的是从 origin_address 给出的最近的 destination_address 中找到。我将在上面编辑我的问题以使其更清楚。 TY
猜你喜欢
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 2021-09-09
相关资源
最近更新 更多