[eluser]HdotNET[/eluser]
Hi all,
I have a table with a parent/child field structure. When querying it is very useful to get an array back that is indexed by the key of each row in the table. This helps when iterating through the results so the parent/child structure can be ordered properly... a classic example of this is a site's navigation.
So far I can't find such a method that does this within the database class.
The closest is this:
Code:
$this->result_object()
Which within the DB_result.php file contains the following code:
Code:
function result_object()
{
if (count($this->result_object) > 0)
{
return $this->result_object;
}
// In the event that query caching is on the result_id variable
// will return FALSE since there isn't a valid SQL resource so
// we'll simply return an empty array.
if ($this->result_id === FALSE OR $this->num_rows() == 0)
{
return array();
}
$this->_data_seek(0);
while ($row = $this->_fetch_object())
{
$this->result_object[] = $row;
}
return $this->result_object;
}
This returns a result set like this:
Code:
Array
(
[1] => stdClass Object
(
[id] => 234
[parent_id] => 0
[name] => Home
)
[2] => stdClass Object
(
[id] => 567
[parent_id] => 234
[name] => About Us
)
[3] => stdClass Object
(
[id] => 890
[parent_id] => 234
[name] => Contact us
)
)
Note the key of the returned array is fairly useless, as in my situation I have to loop through the array to find any object of 'id'
Ideally I need a new method which would be like this:
Code:
function result_object_key($key='')
{
if (count($this->result_object) > 0)
{
return $this->result_object;
}
// In the event that query caching is on the result_id variable
// will return FALSE since there isn't a valid SQL resource so
// we'll simply return an empty array.
if ($this->result_id === FALSE OR $this->num_rows() == 0)
{
return array();
}
$this->_data_seek(0);
while ($row = $this->_fetch_object())
{
if ($key) {
$this->result_object[$row->$key] = $row;
} else {
$this->result_object[] = $row;
}
}
return $this->result_object;
}
When called like this:
Code:
$this->result_object_key('id')
Would return this:
Code:
Array
(
[234] => stdClass Object
(
[id] => 234
[parent_id] => 0
[name] => Home
)
[567] => stdClass Object
(
[id] => 567
[parent_id] => 234
[name] => About Us
)
[890] => stdClass Object
(
[id] => 890
[parent_id] => 234
[name] => Contact us
)
)
Which is a lot more fun to process..
So my question is this, what is the best/C.I. way to extend methods of the Database class?