Hi I'm constructing a html select element like so:
$result = mysql_query("SHOW COLUMNS FROM table") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result))
{
if($row[0] == 'id' || $row[0] == 'tstamp' || $row[0] == 'boiler2oil')
continue;
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
echo '</select>';
The way i've named the columns in the table is rather ugly, with underscores, etc...how can i rename them so i can change the select element display (value 开发者_如何学Gocan stay the same) changes to something a bit more readable and visually pleasing. Is this possible? Would it be some sort of preg_match/preg_replace?
Depends what you want to rename them to. Do you want to do something simple like remove underscores? Is there a rule you can use to clean them all up?
If not, why not add a hash with entries that map from the name in the table to the name you want to print out for the drop-down list?
# map from column name to display name
$labels = array(
'col1' => 'Column 1',
...
);
$result = mysql_query("SHOW COLUMNS FROM table") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result))
{
if($row[0] == 'id' || $row[0] == 'tstamp' || $row[0] == 'boiler2oil')
continue;
# use a more friendly name if one has been defined above in $labels
if(array_key_exists($row[0], $labels))
$label = $labels[$row[0]];
else
$label = $row[0];
echo "<option value='".$row[0]."'>".$label."</option>";
}
echo '</select>';
It can probably done with str_replace
alone, which is more efficient than preg_replace
for simple things like this.
You can define an array which will be having columnName as "key" and Name to Display as "value". Then Echo element of this array rather than displaying column name.
精彩评论