Getting Max Value from an array - php

Hi I am trying to use an api from postcodeanywhere that calcuates the total travel time and distance for a particular journey, and I have got it working using the following code:
//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>";
Which results in the following screenshot
The problem I am having is that the echo shows that it is displaying distance for each journey step, whereas I just want the max value.
I have tried $TotalDistance = max($item["TotalDistance"]). only to get the following error:
max(): When only one parameter is given, it must be an array
Any help would be appreciated.

You can get the max value:
$value = max($array);

What you could do is put the total distance into an array first, then grab the max. Like this:
$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

Related

Loop through associative array and assign values

I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.

Trying to find a way to take a series of values in a json array and add them to an int

Here is my PHP function that grabs data from inputs on the page.
function getCounts($selection, $srch) {
$loadjson = file_get_contents('data.json');
$jsondata = json_decode($loadjson);
$total = 0;
foreach ($jsondata as $list) {
if ($list->$selection == $srch) {
$total .= $list->TOTAL
}
}
echo 'Total - ' . $total . '<br>' . '<br>';
}
I know the issue is with the line "$total .= $list->TOTAL" but I cannot figure out how to take the value that "$list->TOTAL" gets and add it to an integer. I have tested and if I do "echo $list->TOTAL . ','" instead of "$total .= $list->TOTAL" the function spits out a list of all the numbers that are in the JSON data I simply cannot figure out how to get the numbers into an integr and added into one number.
Can someone point me in the right direction?

Error in creating JSON in PHP

I'm very new to PHP and JSON, so I hope you'll excuse my (probably) stupid question.
I'm trying to create a new JSON with fundamental information for my needings, using the information returned by Google Maps API.
Here's the code:
<?php
/**
* Created by PhpStorm.
* User: biagiomontesano
* Date: 22/10/15
* Time: 18:16
*/
function selectLongestSteps($steps_txt, $min_meters)
{
$steps = JSON.parse($steps_txt);
//$steps = json_decode($steps_txt, true);
//$steps = $steps_txt;
echo 'Num of steps: ' . count($steps[0]);
}
function createJsonFromResponse($response_json)
{
// output json
$output_json = '[';
// number of steps
$num_steps = count($response_json['routes'][0]['legs'][0]['steps']);
//echo $num_steps;
// fill the json
for($i = 0; $i<$num_steps; $i++)
{
// start parenthesis
$output_json .= '{';
// start latitude
$output_json .= '"start_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lat'] . ',';
// start longitude
$output_json .= '"start_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['start_location']['lng'] . ',';
// end latitude
$output_json .= '"end_lat":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lat'] . ',';
// end latitude
$output_json .= '"end_lng":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['end_location']['lng'] . ',';
// step length
$output_json .= '"step_length":' . $response_json['routes'][0]['legs'][0]['steps'][$i]['distance']['value']. ',';
// html instruction
$output_json .= '"instruction":"' . $response_json['routes'][0]['legs'][0]['steps'][$i]['html_instructions'] . '"';
// closure parenthesis
$output_json .= '}';
// insert comma if required
if($i != $num_steps-1)
$output_json .= ',';
}
$output_json .= ']';
return $output_json;
}
function get_driving_information($start, $finish)
{
if (strcmp($start, $finish) != 0) {
$start = urlencode($start);
$finish = urlencode($finish);
$url = 'http://maps.googleapis.com/maps/api/directions/json?origin=' . $start . '&destination=' . $finish . '&sensor=false';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return $resp;
}
else
return null;
}
try
{
$info = get_driving_information('via Tiburtina 538, Roma', 'via Ariosto 25, Roma');
$steps = null;
if(!$info)
echo 'No info';
else
$steps = createJsonFromResponse($info);
selectLongestSteps($steps, 200);
//echo $steps;
}
catch(Exception $e)
{
echo 'Caught exception: '.$e->getMessage()."\n";
}
As a test, I asked my function selectLongestSteps to display the number of elements in the JSON.
As you see, I tried to initialise variable $steps in 3 different ways: the last two return a wrong results (0 or 1, while result should be 18).
The first one, that I found on web, returns the following error:
Notice: Use of undefined constant JSON - assumed 'JSON' in /Applications/XAMPP/xamppfiles/htdocs/prova_php/create_json.php on line 11
Fatal error: Call to undefined function parse() in /Applications/XAMPP/xamppfiles/htdocs/prova_php/create_json.php on line 11
I suspect the problem is in creating JSON inside the other function.
Can you help?
Thanks
The problem is this line:
$steps = JSON.parse($steps_txt);
JSON.parse() ist a JavaScript function. You need something like this in PHP
$steps = json_decode($steps_txt);
http://php.net/manual/en/function.json-decode.php
PHP has in-built function to change array to json and vice-verse.
json_encode($array) will give json form of array.
json_decode($json, true) will give your array back from json. If you didn't give true as your second param, you will be getting an object instead of an array.

Wrong Foreach cycle

i am doing something wrong with my foreach cycle. But looks my knowledge is not enugh to figure out what's wrong. My code is pretty simple:
$xnl_file = "xml.xml";
$xml = simplexml_load_file($xnl_file);
$my_file = 0;
foreach ($xml as $value){
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>".$xml->Partnership->CountryOrganizationId."</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>".$xml->Partnership->PartnershipId."</PartnershipId>";
$OwnerId = "<OwnerId>".$xml->Partnership->OwnerId."<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>".$xml->Partnership->PartnerIdList->String."</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>".$xml->Partnership->Contract->CountryOrganizationId."</CountryOrganizationId>";
$ContractId = "<ContractId>".$xml->Partnership->Contract->ContractId."</ContractId>";
$data = "<Partnership>".$CountryOrganizationId.$PartnershipId.$OwnerId.$PartnerIdList.$CountryOrganizationId_contact.$ContractId.$Role1.$Category1.$Rate1.
$Role2.$Category2.$Rate2.$Role3.$Category3.$Rate3."</Partnership>";
echo $data;
}
I am getting data from XML and try to parse it on multiple one, but this just copy same data again and again. I am not sure what i am doing wrong. In my opinion data should rewrite each other every time cycle is doing same but they are not changing. At echo $data i get as many results as i should, problem is just they are same.
If I var_dump $value at start i get nice result that data are coming to cycle but why the output is the same all the time?
Please can somebody give me advise?
Thanks
The $value variable is never used, you're always using the $xml. Try it like:
$xnl_file = "xml.xml";
$xml = simplexml_load_file($xnl_file);
$my_file = 0;
foreach ($xml as $value){
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>" . $value->CountryOrganizationId . "</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>" . $value->PartnershipId . "</PartnershipId>";
$OwnerId = "<OwnerId>" . $value->OwnerId . "<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>" . $value->PartnerIdList->String . "</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>" . $value->Contract->CountryOrganizationId . "</CountryOrganizationId>";
$ContractId = "<ContractId>" . $value->Contract->ContractId . "</ContractId>";
$data = "<Partnership>" . $CountryOrganizationId . $PartnershipId . $OwnerId . $PartnerIdList . $CountryOrganizationId_contact .
$ContractId . $Role1 . $Category1 . $Rate1 . $Role2 . $Category2 . $Rate2 . $Role3 . $Category3 . $Rate3 .
"</Partnership>"afdsf
echo $data;
}
Concat $data to its previous value { $data .= "......"}
foreach ($xml as $value)
{
var_dump($value);
$CountryOrganizationId = "<CountryOrganizationId>".$xml->Partnership->CountryOrganizationId."</CountryOrganizationId>";
$PartnershipId = "<PartnershipId>".$xml->Partnership->PartnershipId."</PartnershipId>";
$OwnerId = "<OwnerId>".$xml->Partnership->OwnerId."<OwnerId>";
$PartnerIdList = "<PartnerIdList><String>".$xml->Partnership->PartnerIdList->String."</String></PartnerIdList>";
$CountryOrganizationId_contact = "<Contract><CountryOrganizationId>".$xml->Partnership->Contract->CountryOrganizationId."</CountryOrganizationId>";
$ContractId = "<ContractId>".$xml->Partnership->Contract->ContractId."</ContractId>";
$data .= "<Partnership>".$CountryOrganizationId.$PartnershipId.$OwnerId.$PartnerIdList.$CountryOrganizationId_contact.$ContractId.$Role1.$Category1.$Rate1.
$Role2.$Category2.$Rate2.$Role3.$Category3.$Rate3."</Partnership>";
}
echo $data;

Getting XML with PHP: how to get attributes from 2 nodes with same name

I am getting attributes from XML nodes and saving them to variables with a for loop as such:
for ($i = 0; $i < 10; $i++){
$group = $xml->Competition->Round[0]->Event[$i][Group];
if($group == "MTCH"){
$eventid = $xml->Competition->Round[0]->Event[$i][EventID];
$eventname = $xml->Competition->Round[0]->Event[$i][EventName];
$teamaname = $xml->Competition->Round[0]->Event[$i]->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->EventSelections[1][EventSelectionName];
echo "<br/>" . $eventid . ": " . $eventname . ", " . $teamaname . "VS" . $teambname;
}//IF
}//FOR
I can save each Event[EventID] and each Event[EventName] but I cannot get the EventSelections[EventSelectionNames] to save.
I am guessing this is because there are multiple (2) <EventSelection>s for each <Event>, this is why I tried to get them individually uising [0] and [1].
The part of the XML file in question looks like:
<Event EventID="1008782" EventName="Collingwood v Fremantle" Venue="" EventDate="2014-03-14T18:20:00" Group="MTCH">
<Market Type="Head to Head" EachWayPlaces="0">
<EventSelections BetSelectionID="88029974" EventSelectionName="Collingwood">
<Bet Odds="2.10" Line=""/>
</EventSelections>
<EventSelections BetSelectionID="88029975" EventSelectionName="Fremantle">
<Bet Odds="1.70" Line=""/>
</EventSelections>
</Market>
</Event>
Can anyone point me in the right direction to save the EventSelectionNames to variables?
Rather than looping and checking for $group, use xpath to select data directly:
$xml = simplexml_load_string($x); // assume XML in $x
$group = $xml->xpath("/Event[#Group = 'MTCH']")[0];
echo "ID: $group[EventID], name: $group[EventName]" . PHP_EOL;
If there are always two <EventSelections>, you can:
echo "Team A: " . $group->Market->EventSelections[0]['EventSelectionName']" . PHP_EOL;
echo "Team B: " . $group->Market->EventSelections[1]['EventSelectionName']" . PHP_EOL;
Otherwise, use foreach:
foreach ($group->Market->EventSelections as $es)
$teamnames[] = $es['EventSelectionName'];
echo "There are " . count($teamnames) . "Teams:" . PHP_EOL;
foreach ($teamname as $teamname) echo $teamname . PHP_EOL;
see it in action: https://eval.in/105642
Note:
The [0] at the end of the code-line starting with $group = $xml->xpath...requires PHP >= 5.4. If you are on a lower version, update PHP or use:
$group = $xml->xpath("/Event[#Group = 'MTCH']");
$group = $group[0];
Michi's answer is more correct and better coded but I also found the adding the node 'Market' to my code worked as well:
$teamaname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[1][EventSelectionName];

Categories