PHP:获取JSON数组中的最高值?

PHP:获取JSON数组中的最高值?,php,json,Php,Json,我使用下面的代码来获取位置之间的距离 <?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(

我使用下面的代码来获取位置之间的距离

<?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如下所示:

{
   "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: 195
因此,当我运行代码时,我会在页面上打印以下内容:

Distance in Miles: 42 
但我需要的是打印出最高的数字。所以它应该是这样的:

{
   "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: 195
有人能就此提出建议吗


提前谢谢

为此,您可以收集数组中的所有
text
,(尝试使用)键,然后使用
max()
查找最大值。为此,您可以收集数组中的所有
text
,(尝试使用)键,然后使用
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);
如果您不想重新转换为英里,您可以对文本字段的浮点值进行缩减


我的猜测是,如果您有一个大型阵列,这是执行此操作最有效的方法。

以下是使用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);
如果您不想重新转换为英里,您可以对文本字段的浮点值进行缩减

我的猜测是,如果你有一个大数组,这是最有效的方法。

使用
array\u column()
你可以提取所有
距离
数组,然后以
文本
作为键和
作为值构建查找:

$array = json_decode($json, true);
$dist  = array_column(array_column($array['rows'][0]['elements'], 'distance'),
                                   'value', 'text');
然后只需计算
max()
,找到它并输出键:

echo array_search(max($dist), $dist);
使用
array\u column()

$array = json_decode($json, true);
$dist  = array_column(array_column($array['rows'][0]['elements'], 'distance'),
                                   'value', 'text');
然后只需计算
max()
,找到它并输出键:

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

我不知道这是不是更简单的方法,但试试看

在屏幕上打印之前执行类似操作

$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
$lenght\u elements=sizeof($oJSON->rows[0])
$array_elements=array();
对于($i=0;$irows[0]->元素[$i]->距离->文本);
阵列推送($array\u elements,$fDistanceInMiles);
}
$max\u value=max($array\u元素);
回声“以英里为单位的距离:”.$max_值//这将打印最高值

注意:如果您也需要遍历这些行,您可以使用另一个循环,您仍然可以得到结果。

我不知道这是否是更简单的方法,但请尝试一下

在屏幕上打印之前执行类似操作

$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
$lenght\u elements=sizeof($oJSON->rows[0])
$array_elements=array();
对于($i=0;$irows[0]->元素[$i]->距离->文本);
阵列推送($array\u elements,$fDistanceInMiles);
}
$max\u value=max($array\u元素);
回声“以英里为单位的距离:”.$max_值//这将打印最高值
注意:如果您也需要遍历这些行,您可以使用另一个循环,您仍然可以得到结果。

保持简单

// 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);
保持简单

// 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);


你是在问我们如何迭代一个数组并检查一个条件是否成立吗?可能是@zod的副本尽管你链接中使用的算法是OP想要的,这是一个PHP问题。你放弃了吗?你是在问我们如何迭代一个数组并检查一个条件来保持吗?可能重复@zod虽然你链接中使用的算法是OP想要的,但这是一个PHP问题。你放弃了吗?很好。我想您也可以排序/反向排序并获取适当的元素,对吗?这就是我需要做的,但是为什么我不能删除“mi”?我试过:$dist=preg_replace('mi',''$dist);回波阵列搜索(最大($dist),$dist);您需要在返回
array_search()
时进行替换,但您可以取
,即米,除以
1609.34
得到英里数。或强制转换为浮点
echo(float)数组\u搜索(最大($dist),$dist)整洁。我想您也可以排序/反向排序并获取适当的元素,对吗?这就是我需要做的,但是为什么我不能删除“mi”?我试过:$dist=preg_replace('mi',''$dist);回波阵列搜索(最大($dist),$dist);您需要在返回
array_search()
时进行替换,但您可以取
,即米,除以
1609.34
得到英里数。或强制转换为浮点
echo(float)数组\u搜索(最大($dist),$dist)我唯一的批评是对数组的不必要转换。@Mikey我已经添加了对象版本。我唯一的批评是对数组的不必要转换。@Mikey我已经添加了对象版本。虽然这个链接可以回答这个问题,但最好在这里包括答案的基本部分,并提供链接供参考。如果链接页面发生更改,仅链接的答案可能无效。-谢谢,@Derek,谢谢你的关注。虽然这个链接可以回答这个问题,但最好在这里包含答案的基本部分,并提供链接供参考。如果链接页面发生更改,仅链接的答案可能无效。-谢谢你,德里克,谢谢你的关心