Michael C. Michael C. - 17 days ago 6
JSON Question

Nested PHP arrays to json

So my code here:

$featurecollection = ("FeatureCollection");

$test[] = array (
"type" => $featurecollection,
$features[] = array($images)

);

file_put_contents($cache,json_encode($test));


results in the following json:

[
{
"type":"feature",
"0":[
[
{
"title":"some title",
"src":"value",
"lat":"value",
"lon":"value"
},
{
"title":"some title",
...


But I need to nest things differently and I'm perplexed on how the php array should be constructed in order to get a result like:

{
"type":"FeatureCollection",
"features":[

{
"type":"Feature",
"geometry":{
"coordinates":[
-94.34885,
39.35757
],
"type":"Point"
},
"properties":{
"latitude":39.35757,
"title":"Kearney",
"id":919,
"description":"I REALLY need new #converse, lol. I've had these for three years. So #destroyed ! :( Oh well. Can't wait to get a new pair and put my #rainbow laces through. #gay #gaypride #bi #proud #pride #colors #shoes #allstar #supporting ",
"longitude":-94.34885,
"user":"trena1echo5",
"image":"http://images.instagram.com/media/2011/09/09/ddeb9bb508c94f2b8ff848a2d2cd3ece_7.jpg",
"instagram_id":211443415
}
},


What would the php array look like for that? I'm thrown off by the way everything is nested but still has a key value.

Answer

Here's how I'd represent that in PHP:

array(
    'type' => 'FeatureCollection',
    'features' => array(
        array(
            'type' => 'Feature',
            'geometry' => array(
                'coordinates' => array(-94.34885, 39.35757),
                'type' => 'Point'
            ), // geometry
            'properties' => array(
                // latitude, longitude, id etc.
            ) // properties
        ), // end of first feature
        array( ... ), // etc.
    ) // features
)

So to get that structure, each feature has to be an associative array of:

  • type,
  • geometry - an associative array of:
    • coordinates - an indexed array of values,
    • type
  • properties - an associative array of values like latitude, longitude, id etc.

It's times like these when I prefer languages that distinguish between lists (array(1, 2, 3)) and dictionaries or maps (array('a' => 1, 'b' => 2)).