note 25692 deleted from control-structures.foreach by philip

From: Date: Mon, 30 Dec 2002 17:44:15 +0000
Subject: note 25692 deleted from control-structures.foreach by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-41477@lists.php.net to get a copy of this message
Here is a nice complicated example from a production environment. (Names of classes and variables have been changed because the software is still very hush-hush around here.) It illustrates the use of foreach() to trace through class object fields, as well as details of using object references as arguments to foreach(). _____________________________ class Record { var $id ; var $stuff1; var $stuff2; function Record( $csv_array ) { $this->id = $csv_array[0] ; $this->stuff1 = $csv_array[1] ; $this->stuff2 = $csv_array[2] ; } // end of Record() function toHTMLrow() { print " <tr>\n" ; foreach( $this as $col => $value ) print " <td>" . $value . "</td>\n" ; print " </tr>\n" ; return ; } // end of toHTMLrow() } // end of Record class class DataTable { var $rows ; // should all be instances of Record function DataTable( $fname ) { $fp = fopen( $fname, 'r' ) while( $row = fgetcsv( $fp, 128 ) ) $this->rows[] = new Record( $row ) ; fclose( $fp ) ; } // end of DataTable() } // end of DataTable class $datatable = new DataTable( 'datafile.csv' ) ; print "<html>\n<body>\n" ; print "<table>\n <thead>\n <tr>\n" ; $firstrow = $datatable->rows[0] ; foreach( $firstrow as $col => $value ) print " <th>" . $col . "</th>\n" ; print " </tr>\n </thead>\n <tbody>\n" ; foreach( $datatable->rows as $index => $row ) if( $index > 0 ) $row->toHTMLrow() ; print " </tbody>\n</table>\n" ; print "</body>\n</html>" ;

« previous php.notes (#41477) next »