wicky wicky - 5 months ago 88
PHP Question

how to get $key value while using result_array in codeigniter

the result_array returns the value but does not return $key in codeigniter, if I manually add a data array in the view it does return $key, Why it does not echo the $key.

Model::

<?php

class Admin_user extends CI_Model
{

public function list_rows()
{
$query = array();
$query = $this->db->get('content');
return $query->result_array();

}

}


View::

<?php
foreach ($get_all_content as $key => $values)
{
$title = $values['title'];
echo "<th>" . $key . "</th>";
}
?>


Controller::

$data['get_all_content'] = $this->admin_user->list_rows();


Print_r ::

Array
(
[0] => Array
(
[id] => 1
[menu_id] => 12
[title] => Register Domain name for free
[sub_title] => This is the sub_title
[content] => this is the content description
[description] =>
[section] =>
)
)

Answer

Try this:

 $yourdata = [0 => 
      ['id' => 1, 'menu_id' => 12, 'title' => 'Register Domain name for free','sub_title' => 'This is the subtitle', 'content' => 'this content', 'description' => 'description', 'section' => 'sect']
 ];

    foreach($yourdata as $key => $val)
    {
        foreach($val as $key2 => $newVal)
        {
            echo '<pre>';
            var_dump($key2, $newVal);
              //or echo it echo $key2 and echo $newVal
        }
    }

resulted output:

  string(2) "id"
    int(1)

  string(7) "menu_id"
    int(12)

  string(5) "title"
  string(29) "Register Domain name for free"

  string(9) "sub_title"
  string(20) "This is the subtitle"

  string(7) "content"
  string(12) "this content"

  string(11) "description"
  string(11) "description"

  string(7) "section"
  string(4) "sect"