2

How can I get the maximum distance from the array below? I am getting the following output when i try to print_r($data):

Array
(
    [0] => Array
        (
            [distance] => 1.7 km
            [time] => 3 mins
            [distance_value] => 1720
            [time_value] => 192
        )

    [1] => Array
        (
            [distance] => 4.2 km
            [time] => 10 mins
            [distance_value] => 4207
            [time_value] => 587
        )

)

I want to echo 4.2 km because it is the max distance in my array.

foreach ($delivery as $key => $value) {
    if($key==0) {
        $mysource = $pickup;
    } else {
        $mysource = $delivery[$key-1];
    }
    $data[$key] = $this->GetDrivingDistance($mysource,$value);
    if(!empty($data[$key])) {
        $dist += max($data[$key]['distance']); 
    }
}
echo $dist; exit();
print_r($data); exit();
4
  • You want to find the max of distance only ?? Commented Jan 10, 2017 at 5:05
  • Is this value 1.7 km or 1.7 ? Commented Jan 10, 2017 at 5:10
  • @all answerers, beware that 4.2 km is a string, not float. Blind conversion gives unpredictable result! You need to convert it appropriately first. Check out my answer Commented Jan 10, 2017 at 5:24
  • @Thamilan Just use distance_value for sorting instead. As far as I can see it contains "distance" in meters as an integer. Commented Jan 10, 2017 at 12:29

6 Answers 6

6

You can make use of built-in functions:

echo max(array_map('floatval',array_column($array, "distance")))." km";

Explanation:

  • array_column - converts your array to single dimensional
  • array_map - Apply float operation to the string. This is important since your string comparison compares two numbers wrongly. When float function is applied your km will be removed, so append later on.

Example for string:

11.7 is less than 4.2, because it compares first character and arranges by 1,2,3...


Output:

4.2 km

Note: This is suitable if all values are in km,if it is in other units, you need a workaround too!

Sign up to request clarification or add additional context in comments.

Comments

0
<?php

$array = array
(
     array
        (
            "distance" => "1.7 km",
            "time" => "3 mins",
            "distance_value" => 1720,
            "time_value" => 192,
        ),

        array
        (
            "distance" => "4.2 km",
            "time" => "10 mins",
            "distance_value" => 4207,
            "time_value" => 587,
        )
);

$distance = [];
$i = 0;
foreach ($array as $distance_data) {
    $distance[] = (float)$distance_data["distance"];
    $i++;
}
$max_distnace = max($distance);
var_dump($max_distnace);

1 Comment

Are you sure you tested your code with dynamic values?
0

You can first sort the array by distance and get the required one:

$myArray = 
array (
    array
        (
            'distance' => '1.7 km',
            'time' => '3 mins',
            'distance_value' => 1720,
            'time_value' => 192,
        ),
    array
        (
            'distance' => '4.2 km',
            'time' => '10 mins',
            'distance_value' => 4207,
            'time_value' => 587,
        )

);

usort($myArray,function($a, $b) {
 return $b['distance_value'] - $a['distance_value'];
});

$maxDistance = $myArray[0];

echo $maxDistance['distance'];
// 4.2 km

3 Comments

if you reverse the usort comparison, you don't need array_reverse usort($data, function ($a, $b){ return $b['distance_value'] - $a['distance_value'];}); and echo $data[0]['distance'];. Here is a demo
Are you sure you tested your code with dynamic values?
distance and distance_value keep the same value. Using distance_value to compare more stable way I think. This code is tested.
0

I get solution from below code..

foreach ($delivery as $key => $value) {
                        if($key==0){
                            $mysource = $pickup;
                        }else{
                            $mysource = $delivery[$key-1];
                        }
                        $data[$key] = $this->GetDrivingDistance($mysource,$value);
                        if(!empty($data[$key])){
                            $max = '-9999999 km'; //will hold max val
                            $found_item = null; //will hold item with max val;
                            foreach($data as $k=>$v)
                            {   
                                if($v['distance']>$max)
                                {
                                   $max = $v['distance'];
                                   $found_item = $v;
                                }
                            }                           
                        }
                    } 
                    $dist = $max;

Comments

0

Thamilan's answer is the best, but as you're using CakePHP you can also use Hash::extract() if array_column() isn't available to you (i.e. you're using an older version of PHP) or if you need to use an array with deeper associations thanks to the Hash utility's path syntax:-

echo max(array_map('floatval', Hash::extract($array, 'distance'))) . ' km';

Here Hash::extract() is working like array_column() and converting your array to a single dimensional array.

Comments

0

Sine this questions is tagged with CakePHP I though I'd give my solution using CakePHP Collection class:

use Cake\Collection\Collection;
(new Collection($data))->sortBy('distance_value')->first()['distance'];

Note that CakePHP has a utility function collection that can make this shorter:

collection($data)->sortBy('distance_value')->first()['distance']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.