簡體   English   中英

PHP:在JSON數組中獲得最高價值?

[英]PHP: Get the highest value in a JSON array?

我正在使用以下代碼來獲取位置之間的距離。

<?php
function curl_request($sURL,$sQueryString=null)
{
        $cURL=curl_init();
        curl_setopt($cURL,CURLOPT_URL,$sURL.'?'.$sQueryString);
        curl_setopt($cURL,CURLOPT_RETURNTRANSFER, TRUE);
        $cResponse=trim(curl_exec($cURL));
        curl_close($cURL);
        return $cResponse;
}

$sResponse=curl_request('http://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=London&destinations=Southend-on-sea|Westcliff-on-sea|Leigh-on-sea|leeds&mode=driving&language=en&sensor=false');
$oJSON=json_decode($sResponse);
if ($oJSON->status=='OK')
        $fDistanceInMiles=(float)preg_replace('/[^\d\.]/','',$oJSON->rows[0]->elements[0]->distance->text);
else
        $fDistanceInMiles=0;

echo 'Distance in Miles: '.$fDistanceInMiles.PHP_EOL;

?>

--

由於以下原因,它將僅獲得JSON響應中的第一個值:

$fDistanceInMiles=(float)preg_replace('/[^\d\.]/','',$oJSON->rows[0]->elements[0]->distance->text);

--

JSON如下所示:

{
   "destination_addresses" : [
      "Southend-on-Sea, UK",
      "Westcliff-on-Sea, Southend-on-Sea, UK",
      "Leigh-on-Sea SS9, UK",
      "Leeds, UK"
   ],
   "origin_addresses" : [ "London, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "42.0 mi",
                  "value" : 67669
               },
               "duration" : {
                  "text" : "1 hour 14 mins",
                  "value" : 4464
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "42.7 mi",
                  "value" : 68723
               },
               "duration" : {
                  "text" : "1 hour 17 mins",
                  "value" : 4646
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "40.1 mi",
                  "value" : 64508
               },
               "duration" : {
                  "text" : "1 hour 10 mins",
                  "value" : 4225
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "195 mi",
                  "value" : 313043
               },
               "duration" : {
                  "text" : "3 hours 39 mins",
                  "value" : 13133
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

因此,當我運行代碼時,我將其打印在頁面上:

Distance in Miles: 42 

但是我需要打印出最大的數字。 所以應該是這樣的:

Distance in Miles: 195

有人可以為此提供建議嗎?

提前致謝。

使用array_column()可以提取所有distance數組,然后使用text作為鍵並使用value作為值來構建查找:

$array = json_decode($json, true);
$dist  = array_column(array_column($array['rows'][0]['elements'], 'distance'),
                                   'value', 'text');

然后只需計算max() ,找到它並輸出密鑰:

echo array_search(max($dist), $dist);

為此,您可以收集數組中的所有text (嘗試使用array_column() )鍵,然后使用max()查找最大值

這是使用array reduce的方法:

<?php

$json = '{
   "destination_addresses" : [
      "Southend-on-Sea, UK",
      "Westcliff-on-Sea, Southend-on-Sea, UK",
      "Leigh-on-Sea SS9, UK",
      "Leeds, UK"
   ],
   "origin_addresses" : [ "London, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "42.0 mi",
                  "value" : 67669
               },
               "duration" : {
                  "text" : "1 hour 14 mins",
                  "value" : 4464
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "42.7 mi",
                  "value" : 68723
               },
               "duration" : {
                  "text" : "1 hour 17 mins",
                  "value" : 4646
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "40.1 mi",
                  "value" : 64508
               },
               "duration" : {
                  "text" : "1 hour 10 mins",
                  "value" : 4225
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "195 mi",
                  "value" : 313043
               },
               "duration" : {
                  "text" : "3 hours 39 mins",
                  "value" : 13133
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}';

$maxDistance = array_reduce(json_decode($json, true)["rows"][0]["elements"], function($accumulator, $item){
   return ($item['distance']['value'] > $accumulator) ? $item['distance']['value'] : $accumulator;
}, 0);


var_dump($maxDistance);

產量:

整數(313043)

這是相同的代碼,沒有不必要的轉換為對象:

$distance = array_reduce(json_decode($json)->rows[0]->elements, 
function($accumulator, $item){
    return ($item->distance->value > $accumulator) ? $item->distance->value : $accumulator;
}, 0);

如果您不想重新轉換為英里,則可以改為減少文本字段的float值。

http://sandbox.onlinephpfunctions.com/code/37176c07b7fc46a713b275e2d3326444b970de1a

我的猜測是,如果陣列很大,這是最高效的方法。

我不知道這是否是更簡單的方法,但是請嘗試一下。

在屏幕上打印之前,請執行以下操作。

$lenght_elements=sizeof($oJSON->rows[0])
$array_elements=array();
for($i=0;$i<$lenght_elements;$i++){
$fDistanceInMiles=(float)preg_replace('/[^\d\.]/','',$oJSON->rows[0]->elements[$i]->distance->text);
array_push($array_elements,$fDistanceInMiles);
}

$max_value=max($array_elements); 

echo echo 'Distance in Miles: '.$max_value; //this should print the highest value

注意:如果您也需要遍歷所有行,則可以使用另一個循環,無論如何您都會得到結果。

把事情簡單化。

// get all elements
$elements = json_decode($oJSON)->rows[0]->elements;

// get all the distances
// array_map() is useful here b/c there is a 1-1 correspondence between an element and its distance
$distances = array_map(function ($element) {
    // convert distance to numeric value to ensure that we are only working with numbers (and not strings)
    return (float) preg_replace('/[^\d\.]/','', $element->distance->text);
}, $elements);

// get the maximum value
echo 'Distance in Miles: ' . max($distances);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM