Оказывается, относительно простое решение заключалось в том, чтобы не объявлять функцию внутри функции. Как только я переместил compare_distance()
за пределы функции findNearestLocation()
, она отлично работает.
Итак, теперь я понимаю, что, но я действительно не понимаю, почему. В чем проблема, возникающая при объявлении функции внутри функции?
Извините, если это кажется очевидной проблемой, я до сих пор новичок в PHP.
<?php
function findNearestLocation($clientLocation) {
global $depotLocations;
$findDepot = $depotLocations;
$count = 0;
foreach ($findDepot as $row) {
$currentDepot = array($row['location_latitude'], $row['location_longitude']);
$findDepot[$count]['distance'] = distance($currentDepot,$clientLocation);
$count ++;
}
function compare_distance($a, $b) {
if ($a['distance'] == $b['distance']) return 0;
return ($a['distance'] < $b['distance']) ? -1 : 1;
}
usort($findDepot, 'compare_distance1');
return $findDepot[0];
}
function distance($depot, $clientLocation) { // need to send two arrays with only longitude and latitude
list($lat1, $lon1) = $depot;
list($lat2, $lon2) = $clientLocation;
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$kilometres = $dist * 60 * 1.1515 * 1.609344;
return $kilometres;
}
// 4. ** These next two lines cause the error. If I comment out either of these lines, the code works fine and returns the expected result.
$finalPickup = findNearestLocation($pickupLocation);
$finalDropoff = findNearestLocation($dropoffLocation);
var_dump($finalPickup);
var_dump($finalDropoff);
?>
Источник: @John Detlefs
Не могли бы вы добавить ошибку, которую вы получаете на свой вопрос, пожалуйста? – Pete
Это не очевидно из вашего описания, о чем вы говорите. (Вы не можете, например, * определить * функцию дважды.) Вы можете, конечно, * называть * столько раз, сколько хотите. –
@PietervandenHam - я получаю ошибку 500 через ajax на консоли –