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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Tyler Fontaine
  • 131
  • 2
  • 12
  • 1
    Start by doing a `print_r($plat_options);` that will show you the array in a pretty readable and understandable format – RiggsFolly May 16 '17 at 15:44

1 Answers1

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!

Community
  • 1
  • 1
JP. Aulet
  • 4,375
  • 4
  • 26
  • 39
  • 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. – Tyler Fontaine May 16 '17 at 15:48
  • Check for my update, you should have access to you data with that. – JP. Aulet May 16 '17 at 15:56
  • 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. – Tyler Fontaine May 16 '17 at 16:05