angel1108
angel1108

Reputation: 333

How to get data from database that result as an array in model codeigniter

I want to make a query that results like this in codeigniter MODEL:

$caldata = array (
   15 => 'yes',
   17 => 'no'
);

Is that possible to do?

Take NOTE: The 15,17 and yes,no are in the same database table.

Upvotes: 0

Views: 1571

Answers (3)

pr1nc3
pr1nc3

Reputation: 8338

you can use result_array() function so you can have something like:

$query = $this->db->select('id,answer')->from('users')->get();

$result = $query->result_array();

print_r($result);

After that you have your array and you can make the $key => $value relation of the fields

Upvotes: 1

angel1108
angel1108

Reputation: 333

After a long search i found an answer. Sample way to do this:

$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();

$datavariable = $query->result();

   $caldata = array();
                foreach($datavariable as $row){
                    $caldata[substr($row->start_date,8,2)] = $row->class;
                }

Upvotes: 0

Rahul
Rahul

Reputation: 18557

There is no core helper function to achieve what you want in CI. But you can create your own helper function:

function pluck($arr = [], $val = '', $key = '') 
{
    // val - label for value in array
    // key - label for key in array
    $result = [];
    foreach ($arr as $value) {
        if(!empty($key)){
            $result[$value[$key]] = $value[$val];    
        }else{
            $result[] = $value[$val];    
        }
    }
    return $result;
}

Upvotes: 1

Related Questions