I consider myself new to PHP. I can make it do whatever I want it to do, but that doesn't make it "right" or the "best way to do it". From a performance standpoint, there always seems to be a "better" way to do it based on code complexity and execution time.
This may be one of those questions that get closed because it's "opinion based" or whatever, but I'm not looking for an opinion. I'm looking for a "leaner and meaner" way of doing this, so that if nothing else I can learn how I can improve.
The following code works. It does exactly what I want it to do. But it seems very... cumbersome. So the question is: what's a cleaner, leaner and meaner way to accomplish this?
Model
public function bdgt_cat_select($id = NULL) {
if ($id == NULL) {
$query = $this -> db -> query("SELECT * FROM bdgt_cat WHERE parent_id = 0");
if ($query -> num_rows() > 0) {
foreach ($query->result() AS $row) {
$array[] = get_object_vars($row);
}
return $array;
}
} else {
$sql = "SELECT * FROM bdgt_cat WHERE parent_id = ?";
$query = $this -> db -> query($sql, $id);
if ($query -> num_rows() > 0) {
foreach ($query->result() AS $row) {
$array[$row->parent_id] = get_object_vars($row);
}
return $array;
}
}
}
Controller
public function index() {
$data['cat_sel'] = $this->read->bdgt_cat_select();
foreach($data['cat_sel'] AS $subcat) {
$data['subcat_sel'] = $this->read->bdgt_cat_select($subcat['id']);
}
$this->stencil->paint('finance/add_transaction', $data);
}
View
<select class="form-control" name="id" id="id">
<option value="">-- SELECT --</option>
<?php
foreach($cat_sel AS $row) {
(int) $rid = $row['id'];
if ((int) $row['parent_id'] === 0) {
echo '<optgroup label="' . $row['cat_label'] . '">';
foreach($subcat_sel AS $sub) {
if ((int) $sub['parent_id'] == $rid) {
echo '<option value="' . $sub['id'] . '">' . $sub['cat_label'] . '</option>';
}
}
echo '</optgroup>';
}
}
?>
</select>
Obviously this is a budget part of a larger project I'm working on. Personal thing. Whatever.
Output
<select class="form-control" name="id" id="id">
<option value="">-- SELECT --</option>
<optgroup label="Manual Adjustment"></optgroup>
<optgroup label="Income">
<option value="3">Placeholder</option>
</optgroup>
</select>
Final Notes
This project is being built in CodeIgniter (this is by no means a "do I need to change frameworks" kind of question). It is purely a personal project. It will probably never show up on the internet anywhere. I can't figure out Git anyway. I may at some point convert it to a Phonegap thing or just run it off some kind of server that runs on my phone. This is why I'm really questioning performance and maintainability.