MySQL
cat_id cat_group cat_name cat_status
1 Vehicles Cars 1
2 Vehicles Motorcycles 1
3 Properties Houses 1
4 Properties Apartments 1
5 Electronics Cameras 1
6 Electronics Gadgets 1
HTML
<select id="category" name="category">
<optgroup label="Vehicles">
<option value="1">Cars</option>
<option value="2">Motorcycles</option>
</optgroup>
<optgroup label="Properties">
<option value="3">Houses</option>
<option value="4">Apartments</option>
</optgroup>
<optgroup label="Electronics">
<option value="5">Cameras</option>
<option value="6">Gadgets</option>
</optgroup>
</select>
PHP
function cat_option()
{
global $db;
}
Question
How do I create a php function for the loop of categories? So on the form I just call it by cat_option()
and the results will looks like on HTML
You can do it in one single query, using multi-dimensional arrays:
<?php
$opts = array();
# select all active categories
$qr = mysql_query('SELECT cat_id, cat_group, cat_name FROM categories WHERE cat_status = 1 ORDER BY cat_id ASC');
# go through all results
while ($qa = mysql_fetch_assoc($qr)) {
$opts[$qa['cat_group']][$qa['cat_id']] = $qa['cat_name'];
# e.g. $opts['Vehicles'][1] = 'Cars'
}
/*
# now your array looks like:
$opts = array(
'Vehicles' => array(
1 => 'Cars',
2 => 'Motorcycles',
),
'Properties' => array(
3 => 'Houses',
4 => 'Apartments',
),
'Electronics' => array(
5 => 'Cameras',
6 => 'Gadgets',
)
);
*/
?>
<!-- now output it -->
<select id="category" name="category">
<?php foreach (array('Vehicles', 'Properties', 'Electronics') as $label): ?>
<optgroup label="<?php echo $label ?>">
<?php foreach ($opts[$label] as $id => $name): ?>
<option value="<?php echo $id ?>"><?php echo htmlspecialchars($name); ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>
Assuming the number of elements in catalog will be small enough. You have to first get all the elements by using your SQL query.
Then you could sort those elements based on their values of cat_group. This way, items of similar category will be together. I am assuming you can apply sorting to object collection based on a particular attribute.
Then all you need to do is traverse the list and create new optgroup as needed.
You probable want to use a DISTINCT
query to get the different kind of cat_group
's first. Then loop through those creating your optgroup
's.
$opts[$qa['cat_group']][$qa['cat_id']] = $qa['cat_name'];