note 46179 deleted from function.eval by tomsommer

From: Date: Fri, 01 Oct 2004 20:46:02 +0000
Subject: note 46179 deleted from function.eval by tomsommer
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-77707@lists.php.net to get a copy of this message
Note Submitter: t0rus at dr dot com ---- this is a way to eval() an associative array. i was struggling with this for about an hour, posting it, just in case someone like me has the same problem. maybe u'll also find it useful for creating a configuration file for mysql database systems <?php $tables = array(); $tables[count($tables)]= 'Box'; $tables[count($tables)]= 'Ups'; $tables[count($tables)]= 'Dock'; $Box = array( 'FieldNames' => array( 'Field1', 'FieldID', 'ID' ), 'FieldParams'=>array( 'varchar(50)', 'int UNSIGNED NOT NULL', 'int UNSIGNED AUTO_INCREMENT' ) ); $BoxKey = 'ID'; $BoxUnique = array(); $BoxParams = "Type = MyISAM"; $Ups = array( 'FieldNames'=>array( 'User', 'Pwd', 'ID' ), 'FieldParams'=>array( 'varchar(16) NOT NULL', 'varchar(35) NOT NULL', 'int UNSIGNED AUTO_INCREMENT' ) ); $UpsKey = 'ID'; $UpsUnique=array('User'); $UpsParams = "Type = InnoDB"; $Dock = array( 'FieldNames'=>array( 'Company', 'Address', 'ID' ), 'FieldParams'=>array( 'varchar(255)', 'varchar(255)', 'int UNSIGNED AUTO_INCREMENT' ) ); $DockKey = 'ID'; $DockUnique = array(); $DockParams = "Type = HEAP"; foreach ($tables as $TableName){ $query='CREATE TABLE '.$TableName.'('; $TableName="\$".$TableName; eval("\$tblfields = $TableName;"); for ($i=0;$tblfields['FieldNames'][$i+1];$i++){ $query.=$tblfields['FieldNames'][$i].' '.$tblfields['FieldParams'][$i].', '; } //adding keyfield if specified $tblparams = $TableName."Key"; eval("\$tblparam = $tblparams;"); $query.=$tblfields['FieldNames'][$i].' '.$tblfields['FieldParams'][$i]; $query.=(strlen($tblparam)>0)?', PRIMARY KEY('.$tblparam.')':''; //adding unique fields $tblparams = $TableName."Unique"; eval("\$tblparam = $tblparams;"); if (count($tblparam)>0){ $query.=', Unique('; for($i=0;$tblparam[$i];$i++) $query.=$tblparam[$i].', '; $query=substr($query,0,strlen($query)-2); $query.=')'; } //any additional parameters $params=$TableName."Params"; eval("\$params = $params;"); $query.=') '.$params.';'; echo $query."\n"; } ?> the output: CREATE TABLE Box(Field1 varchar(50), FieldID int UNSIGNED NOT NULL, ID int UNSIGNED AUTO_INCREMENT, PRIMARY KEY(ID)) Type = MyISAM; CREATE TABLE Ups(User varchar(16) NOT NULL, Pwd varchar(35) NOT NULL, ID int UNSIGNED AUTO_INCREMENT, PRIMARY KEY(ID), Unique(User)) Type = InnoDB; CREATE TABLE Dock(Company varchar(255), Address varchar(255), ID int UNSIGNED AUTO_INCREMENT, PRIMARY KEY(ID)) Type = HEAP;

« previous php.notes (#77707) next »