tags:

views:

35

answers:

2

I have a table like this:

id | username | email
---+----------+----------------
 1 |     John | [email protected]
17 |     Mary | [email protected]

And I want to get a result like this:

array(
  1 => array(
    username => 'John',
    email => '[email protected]'
  ),
  17 => array(
    username => 'Mary',
    email => '[email protected]'
  )
);

Is it possible to do with built-in functions in CodeIgniter?

+2  A: 

to the best of my knowledge there no built in functions for the same, though you can create a base model, extend it and create a function for the same,

<?php
//Assuming $dbdata is the data returned as an array from database
$result = array();
if(!empty($dbdata))
{
  foreach($dbdata as $key=>$value)
  {
    $id = $value['id'];
    $result[$id] = array( 'username' => $value['username'],
                          'email'=>$value['email'];
                         );
   }
    return $result;
}
?>
Sandy
+1  A: 

Answering my own question:

I've created a helper:

function assoc_by($key, $array) {
    $new = array();
    foreach ($array as $v) {
        if (!array_key_exists($v[$key], $new))
            $new[$v[$key]] = $v;
    }
    return $new;
}

Which can be used like this:

$rows = assoc_by('id', $this->db->get_where(...)->result_array());
Alisey