简体   繁体   中英

PHP : create a specific array from MySQL database

I'd like to build an array from (among other) data stored in a MySQL Database.

My code is the one :

<?php

// STUFF ABOUT CONNECTION TO DATABASE

// Informations about host, login and so on

$query = 'SELECT * FROM maj';
$dbquery = mysql_query($query);

// Parse the dbquery

$geojson = array(
'type' => "FeatureCollection",
'features' => $feature
 );

while($row = mysql_fetch_assoc($dbquery)) {
    $feature = array(
        'location' => $row['location'], 
      'geometry' => array(
      'type' => 'Point')
        );

array_push($geojson, $feature);
}

// Return routing result
print_r($geojson);

?>

I get the following array (first two elements) :

Array
(
    [type] => FeatureCollection
    [features] => 
    [0] => Array
    (
        [location] => Hollywood, CA
        [geometry] => Array
            (
                [type] => Point
            )

    )

    [1] => Array
    (
        [location] => Ventura County
        [geometry] => Array
            (
                [type] => Point
            )

    )

)

BUT I want to get an array with that content (with 'features' having an array inside too) :

Array
(
    [type] => FeatureCollection
    [features] => Array
      (
        [0] => Array
            (
                [location] => Hollywood, CA
                [geometry] => Array
                    (
                        [type] => Point
                    )

            )

        [1] => Array
            (
                [location] => Ventura County
                [geometry] => Array
                    (
                        [type] => Point
                    )

            )
       )
  )

How could I do ?
Thank you very much !

Hope this works

$geojson = array(
    'type' => "FeatureCollection",
    'features' => array()
);

array_push($geojson['features'], $feature);

Initialize $feature and pass it as a reference to $geojson :

$feature = array();
$geojson = array(
  'type' => "FeatureCollection",
  'features' => &$feature
);

Remove the array_push() and just append-assign it to $feature :

while($row = mysql_fetch_assoc($dbquery)) {
    $feature[] = array(
      'location' => $row['location'], 
      'geometry' => array(
      'type' => 'Point')
    );

   // the above is sugar for: array_push($feature, array( 'location' => ... ) );
}

Your call to print_r() should produce the results you're expecting now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM