Create an array that meets certain conditions in PHP

0

We have a database with workshops and their coordinates. Once the data is passed to an array, we measure the distance from the location point entered on a map (or by geolocation) and the nearest workshops.

I do a foreach to collect the coordinates of each workshop, as shown in the image, and I need to collect in another array only the workshops whose distance is lower, to then pass them through JSON.

The problem is that when doing:

if (distancia_a $distancia) { 
  array_push($data, $resultado); 
} 

Only the first workshop picks me up and ignores the rest.

Could you help me out?

    $coorYLocat=$coords['lat'];
    $coorXLocat=$coords['lng'];

    $RadYLocat=($coorYLocat*pi())/180;
    $RadXLocat=($coorXLocat*pi())/180;

    }
    $stmt->execute();
    // $stmt->debugDumpParams();
    $data=$stmt->fetchAll(PDO::FETCH_ASSOC);
    $RADIOTIERRA = '6371';
    $i=0;

    foreach ($data as $taller => $resultado);
    {

        $coorYTaller=$resultado['coordinate_y'];
        $coorXTaller=$resultado['coordinate_x'];

        $RadYTaller=($coorYTaller*pi())/180;
        $RadXTaller=($coorXTaller*pi())/180;
        $distance_a = acos(sin($RadYLocat)*sin($RadYTaller) + cos($RadYLocat) * cos($RadYTaller) * cos ($RadXLocat-$RadXTaller)) * $RADIOTIERRA;

        if ($distance_a <= $distance)
        {
            array_push($datos, $resultado);
        }
    }

echo json_encode($datos);
    
asked by Kora 13.04.2018 в 11:35
source

2 answers

1

I have found the solution and I share it in case someone has more problems like this one. I have left the foreach aside and I used a for.

$distance=x //Distancia introducida por el usuario mediante un slide en HTML
$coorYLocat=$coords['lat'];
$coorXLocat=$coords['lng'];

$RadYLocat=($coorYLocat*pi())/180;
$RadXLocat=($coorXLocat*pi())/180;

}
$stmt->execute();
// $stmt->debugDumpParams();
$data=$stmt->fetchAll(PDO::FETCH_ASSOC);

$RADIOTIERRA = '6371';
$resultado=array();

for ($i=0; $i<=(count($data)-1); $i++)
{
    $coorYTaller=$data[$i]['coordinate_y'];
    $coorXTaller=$data[$i]['coordinate_x'];

    $RadYTaller=($coorYTaller*pi())/180;
    $RadXTaller=($coorXTaller*pi())/180;

    $distance_a = acos(sin($RadYLocat)*sin($RadYTaller) + cos($RadYLocat) * cos($RadYTaller) * cos ($RadXLocat-$RadXTaller)) * $RADIOTIERRA;

    if ($distance_a <= $distance)
    {
        array_push($resultado,$i);
    }
}

echo json_encode($resultado);
    
answered by 15.04.2018 в 00:31
0

Check this link to see if it can help you:

Define if a point (geographic coordinate) is in an area of the map

    
answered by 13.04.2018 в 11:44