如何使用mysqlphp创建自定义json数据


How to create custom json data using mysql php

如何创建这样的json数据:-

 areas: [
             {
            id: "US",
            images: [
                {
                    imageURL: "images/icon.png",
                    latitude: 40.639751,
                    longitude: -73.778925,
                    width: 24,
                    height: 24,
                    title: "New York JF Kennedy",
                }
                ]
                }
                ]

使用php-mysql查询。。表格结构如:-

CREATE TABLE `table` (
  `id` INT(11) NOT NULL,
  `aportname` VARCHAR(200) NOT NULL,
  `country` VARCHAR(200) NOT NULL,
   `latitude` DOUBLE NOT NULL,
  `longitude` DOUBLE NOT NULL,
  `country_code` VARCHAR(4) NOT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=MYISAM DEFAULT CHARSET=latin1

如何编写查询。。。?

使用PDO,确保您的表具有所需的所有值,并根据需要进行调整:

完整示例:

class MySql
{
    private $sDbName      = '';
    private $sUsername    = '';
    private $sPassword    = '';
    private $sHost        = '';
    private $oConnection  = null;
    public function __construct()
    {
        $this->oConnection = new PDO( 
            'mysql:host=' 
            . $this->sHost 
            . ';dbname=' 
            . $this->sDbName, 
            $this->sUsername, 
            $this->sPassword 
            );
    }
    public function getDb()
    {
        return $this->oConnection;
    }
}
    $oMySql = new MySql;
    $oDb = $oMySql->getDb();
    $sSql = "
        SELECT
        country,
        latitude,
        longitude,
        country_code
        FROM table
        LIMIT 1;";
    $oStmp = $oDb->prepare( $sSql );
    $oStmp->execute();
    $aResults = $oStmp->fetchall();
    // var_dump( $aResults );
    if( !empty( $aResults ) )
    {
        // var_dump( $oErrors );
        $aDetail[ 'imageURL' ]  = 'my static url';
        $aDetail[ 'latitude' ]  = $aResults[ 0 ][ 'latitude' ];
        $aDetail[ 'longitude' ] = $aResults[ 0 ][ 'longitude' ];
        $aDetail[ 'width' ]     = '24';
        $aDetail[ 'height' ]    = '24';
        $aDetail[ 'title' ]     = 'my static title';
        $aTmp[ 'id' ]           = $aResults[ 0 ][ 'country' ];
        $aTmp[ 'images' ]       = $aDetail;
        $aFormatted[ 'id' ]     = $aTmp;
    }
    // $oErrors = $oStmp->errorInfo();
$sJson = json_encode( $aFormatted );