Welcome Guest, Not a member yet? Register   Sign In
Extending DB_Result
#1

[eluser]Unknown[/eluser]
I posted this thread in "Ignite Code" and didn't receive any reply, I hope maybe someone here will be able to help me. Sorry for spamming.

I have a very needed db function that I’m using in other projects that are not based on CodeIgniter.

When using a function to return rows from a query (same like $res->result_array()), I give an extra parameter to be used as index field for the array keys.

For example, if I have countries table, with code & name, instead of (example syntax):
countries[0] = array(code: US, name: united states)
countries[1] = array(code: TH, name: thailand)

I want to receive (by calling the function $res->result_array(‘code’)):
countries[‘US’] = array(code: US, name: united states)
countries[‘TH’] = array(code: TH, name: thailand)

To add this functionality, I need to override DB_Result->result_array()

I tried to find simple ways to do it, but couldn’t. I read http://codeigniter.com/wiki/Extending_Database_Drivers/ but it didn’t help.

If anyone can help with a solution, I’ll be very happy. I believe this functionality should be part of CodeIgniter core code, since it’s very useful and doing it in the core saves a lot of extra processing, but I’ll settle for a solution to extend DB_Result Smile
#2

[eluser]davidbehler[/eluser]
There is no easy way to extend the database drivers. They are not like the other libraries and not meant to be extended.

What you can do is edit the core files but you have to be careful here as new versions of CI may bring changes to files to edited and you would have to do this again.

In your case I guess I would go for a small function in a helper.
Let's say you put db_helper.php in your application/helpers folder and in this new file you could a new function like this:
Code:
<?php

function alter_index($result_array, $new_index)
{
  $new_result_array = array();
  foreach($result_array as $key => $value)
  {
    $new_result_array[$value[$new_index]] = $value;
  }

  return $new_result_array;
}
In your model you could use it like this:
Code:
function get_stuff()
{
  //...sql stuff
  return alter_index($res->result_array(), 'code');
}
Be aware that this is untested and as soon as (to use your example) 2 countries have the same code, the later one would override the first one and you would end up with less entries than you had before.
#3

[eluser]Unknown[/eluser]
Thanks, thats a nice solution, obviosuly, much better than changing the core code.




Theme © iAndrew 2016 - Forum software by © MyBB