note 25692 added to control-structures.foreach

From: Date: Wed, 02 Oct 2002 14:05:12 +0000
Subject: note 25692 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-37545@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>" ; -- http://www.php.net/manual/en/control-structures.foreach.php http://master.php.net/manage/user-notes.php?action=edit+25692 http://master.php.net/manage/user-notes.php?action=delete+25692 http://master.php.net/manage/user-notes.php?action=reject+25692

« previous php.notes (#37545) next »