25Nov/090
Define an array of data with PHP and JSON
Something I've always wanted was a way to store an array of data within a PHP define variable.
The only solution I've come up with for this is to store JSON text in the define then decode it into an array when the data is needed.
My example will store some settings used to connect to a database.
Firstly you've got to define DBCONFIG using JSON
define('DBCONFIG', '{"aDbHost":"localhost","aDbUser":"root","aDbPass":"hello1","aDbName":"mydatabase","debugging":"false"}');
Load the JSON into an array using:
$aConfigArray = json_decode(DBCONFIG, true);
// true tells the function to return an array not an object
Now you can extract the array into seperate variables.
extract($aConfigArray);
Once you've extracted all of the variables you can use them however you need.
$aDb = mysql_connect($aDbHost, $aDbUSer, $aDbPass); mysql_select_db($aDbName);
or
print 'Host: '. $aDbHost; print 'User: '. $aDbUser; print 'Pass: '. $aDbPass; print 'DB Name: '. $aDbName;
Outputs:
Host: localhost
User: root
Pass: hello1
DB Name: mydatabase










