Alex Alex - 3 months ago 7
Javascript Question

Declaring Large Object Array in PHP as javascript Arguments

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:


  1. Is this the best way of declaring the object classes with regarding to filling the array with a very large number of co-ordinates, and

  2. Why is PHP giving a warning for the code on lines, 13 and 16 regarding empty values, i.e.




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?

Answer

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