How would I turn this sample if else statement into an array to use as an echo statement / function?
I have some Categories (numbers) in a MYSQL database that I am trying to echo and match up with a Category Name. eg. (1 = Mountain Bike, 2 = Road, 3 = Cyclocross)
I think I need to make an array or function to make this easier 开发者_JS百科on myself when I echo the $event_type, what do you guys think?
if ($row_Recordset1['event_type'] == '1') echo 'Mountain Bike';
else if ($row_Recordset1['event_type'] == '2') echo 'Road';
else if ($row_Recordset1['event_type'] == '3') echo 'Cyclocross';
Thanks in advance!
try something like this
$event_types = array(1 => 'Mountain Bike', 2 => 'Road', 3 => 'Cyclocross');
echo $event_types[$row_Recordset1['event_type']];
A purely PHP solution would be to put the categories into an array and then just dereference at output time:
$categories = array(
1 => 'Mountain Bike',
2 => 'Road',
3 => 'Cyclocross'
);
echo $categories[$row_Recordset1['event_type']];
A better solution would be to put those categories into your database. Then you can join up that categories table and pull up the category names along with the category IDs at query time:
SELECT ..., categories.name
FROM sometable
LEFT JOIN your_categories ON sometable.categoryID = categories.ID
Adapt this code for that:
$array = array('Mountain Bike', 'Road', 'Cyclocross');
echo $array[(int) $row_Recordset1['event_type'] -1];
It may or may not be more efficient, depending on what you store in your database.
If you have the Category (e.g. 1) and Category Label (e.g. Mountain Bike) in each row:
$categories = array();
$result = mysql_query( "SELECT * FROM yourTable" );
while( $row = mysql_fetch_assoc( $result )
$categories[$row['event_type']] = $row['CategoryName'];
Using that method, your ending array would look like this:
array( 1 => "Mountain Bike", 2 => "Road", 3 => "Cyclocross" );
That way you can just do:
echo( $categories[$row_Recordsset1['event_type']] ); // Outputs key value in array
Alternatively,
You can just populate the array yourself:
$categories = array( 1 => "Mountain Bike", 2 => "Road", 3 => "Cyclocross" );
Then use the same echo method I posted above.
精彩评论