开发者

Retrieve data from database as a set of rows indexed by primary key in CodeIgniter

I have a table like this:

id | username | email
---+----------+----------------
 1 |     John | john@example.开发者_开发百科com
17 |     Mary | mary@example.com

And I want to get a result like this:

array(
  1 => array(
    username => 'John',
    email => 'john@example.com'
  ),
  17 => array(
    username => 'Mary',
    email => 'mary@example.com'
  )
);

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


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());


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;
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜