Sunday, January 16, 2022

[FIXED] how to get maximum value from array php

Issue

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

Solution

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;


Answered By - parcel pik

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.