Welcome Guest, Not a member yet? Register   Sign In
Add index_by() method to Query Builder
#1
Lightbulb 

Hello!

How about adding index_by() method to DB Query Builder or DB result (maybe in 3.2 release)?
It will be helpful functionality and does not break the old code.

Example of implementation:

PHP Code:
    public function index_by($field_name)
    {

        if (
count($this->result_array) > 0)
        {
            
$new_array = array();

            foreach (
$this->result_array as $item)
            {
                
$new_array$item[$field_name] ] = $item;
            }

            
$this->result_array $new_array;
        }

        if ((
$c count($this->result_object)) > 0)
        {
            for (
$i 0$i $c$i++)
            {
                
$this->result_object[$this->result_object[$i]->$field_name] = $this->result_object[$i];
                unset(
$this->result_object[$i]);
            }
        }

        
is_null($this->row_data) OR $this->data_seek(0);
        while (
$row $this->_fetch_assoc())
        {
            
$this->result_array$row[$field_name] ] = $row;
        }

        return 
$this;
    } 

Example of using:
PHP Code:
$this->db->get('elements')->index_by('slug')->result_array(); 

Result data:
Code:
Array
(
   [one] => Array
       (
           [id] => 1
           [slug] => one
           [name] => One
           [parent] => 0
       )

   [two] => Array
       (
           [id] => 2
           [slug] => two
           [name] => Two
           [parent] => 1
       )

   [three] => Array
       (
           [id] => 3
           [slug] => three
           [name] => Three
           [parent] => 2
       )
)

I do not have enough knowledge about CodeIgniter code-base for try to add this method by pull-request on GitHub.
And I want to know opinion of CI developers and community about this.

That's why I'm here)
Reply
#2

Has been suggested before. I don't like it, can break if the column doesn't have a constraint.

And it's not like it's hard to do ...

Code:
// $result is whatever result_array() gave you
// $slug is your index
$result = array_combine(array_column($result, $slug), $result);
Reply
#3

(01-21-2018, 11:36 PM)Narf Wrote: Has been suggested before. I don't like it, can break if the column doesn't have a constraint.

And it's not like it's hard to do ...

Code:
// $result is whatever result_array() gave you
// $slug is your index
$result = array_combine(array_column($result, $slug), $result);

Yes, I know, it is not difficult to do. But if it will be a part of Query Builder it will be cleaner and more beautiful.

Anyway, it is not critical feature. Thanks for reply!
Reply
#4

When you fetch data by database then you can use result(); and after that you can combine two array using array_combine() function.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB