I need to pass a PHP array to a javascript function where the array has the form
var Waypoints = [{"Geometry":{"Latitude":52.34,"Longitude":55.35}},{"Geometry":{"Latitude":55.34,"Longitude":56.35}}]
Here is a code snippet:
class Geometry
{
public $Latitude;
public $Longitude;
}
class WayPoint
{
public $Geometry;
}
$Geometry = new Geometry();
$wp = new WayPoint();
$wp->Geometry->Latitude = 52.34;
$wp->Geometry->Longitude = 55.35;
$wp2 = new WayPoint();
$wp2->Geometry->Latitude = 55.34;
$wp2->Geometry->Longitude = 56.35;
$php_data = [$wp,$wp2 ];
echo json_encode($php_data);
which produces this:
[{"Geometry":{"Latitude":52.34,"Longitude":55.35}},{"Geometry":{"Latitude":55.34,"Longitude":56.35}}]
This is the correct array structure, however I am asking two questions:
Warning: Creating default object from empty value in for $wp->Geometry->Latitude = 52.34; and $wp2->Geometry->Latitude = 55.34;
From what I can discern from the documentation, this is the correct way of declaring an object, and why is it just the first variable is being flagged?
The error is because you dont assign the Geometry
property of the Waypoint
objects.
It still works because php will create a default object (called a stdClass
) when you assign a property to a non existent variable.
There is a much simpler solution - json_encode will take an asociative array as input:
echo json_encode(
[
[
'Geometry'=>
[
'Latitude' => 52.34,
'Longtitude'=> 55.35,
]
],
[
'Geometry'=>
[
'Latitude' => 52.65,
'Longtitude'=> 56.35,
]
],
]
);
Obviously you can build this array in a loop.
If you do want to use named classes, for other reasons, then the correct code would be:
class Geometry
{
public $Latitude;
public $Longitude;
}
class WayPoint
{
public $Geometry;
}
$data=[];
$wp = new WayPoint();
$gm = new Geometry();
$gm->Latitude = 52.34;
$gm->Longitude = 55.35;
$wp->Geometry = $gm;
$data[]=$wp;
echo json_encode($data);
Taking both Steve's comments and Barmar's comments (regarding the use of a constructor) I was able to simplify the implementation a little more and making neater. I hope this helps someone looking to do the same thing.
class Geometry
{
public $Latitude;
public $Longitude;
}
class WayPoint
{
public function __construct($Lat, $Long)
{
$geometry = new Geometry();
$geometry->Latitude = $Lat;
$geometry->Longitude = $Long;
$this->Geometry = $geometry;
}
}
$wp = new WayPoint(52.34,68.89);
$wp2 = new WayPoint(55.45,67.89);
$php_data = [$wp,$wp2 ];
echo json_encode($php_data);