1

I simply want to know how to access array elements retrieved from a database. I have the following code to get the names of each item in my database.

$plat_options = $this->db->get('tblplatform_options')->select('name')->result();

How do I go about accessing the name from the array $plat_options? Typically I would do $plat_options[0] for the first element in C#, how is this done in php/codeigniter?

2

1 Answer 1

3

In PHP/Codeigniter, can be done in the same way:

$plat_options[0] //if you have this element, usually is better to check if exists. 

You can retrieve all the elements with foreach($plat_options as $option){...} You can cast to object: https://www.kathirvel.com/php-convert-or-cast-array-to-object-object-to-array/

Or use a Codeigniter Helper (assuming you are using CI3): http://www.codeigniter.com/user_guide/helpers/array_helper.html

I recomend to know which is your array format and retrieve that way (if you don't know, you can do a: var_dump($plat_options) ) to know if is an associative array.

You can use the result_array() function:

$data = $plat_options->result_array();
echo($data[0]['name']);

or:

$data = array_shift($q->result_array());
echo($data['name']);

I extracted this last part from: Codeigniter $this->db->get(), how do I return values for a specific row? that you could check too.

If you don't know a lof of CI, the best you can do is do a simple tutorial to understand how the data + ActiveRecord works.

Hope it helps!

Sign up to request clarification or add additional context in comments.

3 Comments

since I'm using the info in a model I'm not sure how to actually view the var_dump. I'm super new to CI so I still have a ton to learn.
Check for my update, you should have access to you data with that.
Yup so the ['name'] part of $data[0]['name'] is what I was missing. I thought because it was only grabbing the names it wouldn't need the 'name' attribute to access it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.