从数组中获取最大值

时间:2015-05-31 19:19:11

标签: php

您好我正在尝试使用postcode中的api来计算特定旅程的总旅行时间和距离,并且我使用以下代码进行操作:

//Build URL Request
$url = "http://services.postcodeanywhere.co.uk/DistancesAndDirections/Interactive/Directions/v2.00/xmla.ws?";
$url .= "&Key=" . urlencode($Key);
$url .= "&Start=" . urlencode($Start);
$url .= "&Finish=" . urlencode($Finish);
$url .= "&DistanceType=" . urlencode($DistanceType);

//Make the request to Postcode Anywhere and parse the XML returned
$file = simplexml_load_file($url);

//Check for an error, if there is one then throw an exception
if ($file->Columns->Column->attributes()->Name == "Error") 
{
throw new Exception("[ID] " . $file->Rows->Row->attributes()->Error . " [DESCRIPTION] " . $file->Rows->Row->attributes()->Description . " [CAUSE] " . $file->Rows->Row->attributes()->Cause . " [RESOLUTION] " . $file->Rows->Row->attributes()->Resolution);
}

//Copy the data
if ( !empty($file->Rows) )
{
foreach ($file->Rows->Row as $item)
{
$Data[] = array('SegmentNumber'=>$item->attributes()->SegmentNumber,'StepNumber'=>$item->attributes()->StepNumber,'Action'=>$item->attributes()->Action,'Description'=>$item->attributes()->Description,'Road'=>$item->attributes()->Road,'StepTime'=>$item->attributes()->StepTime,'StepDistance'=>$item->attributes()->StepDistance,'TotalTime'=>$item->attributes()->TotalTime,'TotalDistance'=>$item->attributes()->TotalDistance);


$TotalDistance = ($item["TotalDistance"] * 0.000621371192);


echo $TotalDistance."<br>";

这导致以下screenshot

我遇到的问题是回声显示它显示的是每个旅程步骤的距离,而我只想要最大值。

我试过了$TotalDistance = max($item["TotalDistance"])。只是为了得到以下错误:

max(): When only one parameter is given, it must be an array

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以获得最大值:

$value = max($array);

答案 1 :(得分:0)

你可以做的是先将总距离放入数组,然后抓住最大值。像这样:

$distance_array = new array();

foreach ($file->Rows->Row as $item)
{
    $Data[] = array('SegmentNumber'=>$item->attributes()->SegmentNumber,'StepNumber'=>$item->attributes()->StepNumber,'Action'=>$item->attributes()->Action,'Description'=>$item->attributes()->Description,'Road'=>$item->attributes()->Road,'StepTime'=>$item->attributes()->StepTime,'StepDistance'=>$item->attributes()->StepDistance,'TotalTime'=>$item->attributes()->TotalTime,'TotalDistance'=>$item->attributes()->TotalDistance);

    $TotalDistance = ($item["TotalDistance"] * 0.000621371192);

    array_push($distance_array, $TotalDistance); //add the distance to an array

}

echo max($distance_array);

http://php.net/manual/en/function.array-push.php

http://php.net/manual/en/function.max.php