menú multinivel con codeigniter

i'm trying to create a multilevel list. I have two tables 'State' and 'City'. The city table has a foreign key 'state_id' which is the primary key of 'State' table. I want to show each state and under each state there is multiple cities. But when i run my code only the last stored state in the db and the cities under it show up. I want all the states in the Db and the cities corresponds to it to appear.

Part of my controller:

function index(){
    $result = $this->db->count_all('state');

    $id=1;
    while ($id<=$result){
        $data ['state'] = $this->state_model->stateid($id);  
        $data['city']=$this->state_model->statec($id);
        $id++;
    } 
    $this->load->view('state_view',$data);
}

El modelo:

function stateid($id = 0){
    $this->db->where('id',$id);

    $sql = $this->db->get('state');

    return $sql->result();
}

function statec($id = 0){
    $this->db->where('state_id',$id);

    $sql = $this->db->get('city');

    return $sql->result();
}

La vista:

<?php foreach($state as $row):?>
    <h4><?php echo $row->statename;?></h4>
    <?php foreach($city as $row):?>
        <?php echo $row->cityname; ?></br></br></br>
    <?php endforeach;?></br></br>
<?php endforeach;?></br></br>

preguntado el 08 de noviembre de 11 a las 17:11

1 Respuestas

That is because in that while, with every iteration you overwrite the $data['state'] and $data['city']... so only the last iteration gets sent to the view.

You should look more into what arrays and especially multi-dimensional arrays work and how to use them.

That being said, you have bigger problems to consider. Like the code is very badly optimised and will cause problems later. Like your code assumes that the ids in the state table are consecutive, which is not necessarily true.

Here is a rought ideea what your code should look like:

modelo

function get_cities(){

  $states = $this->db->get('state');

  foreach ($states->result() as $state){
    $cities = $this->db->get_where('city', array('state_id', $state->id));
    $state->cities = $cities->result();
  }

  return $states;
}

controlador

function index(){
  $this->load->model('state_model);
  $data['states'] = $this->state_model->get_cities();
  $this->load->view('states/index, $data);
}

ver:

<?php foreach($states as $state):?>
  <h4><?php echo $state->statename;?></h4>
  <?php  foreach($state->city as $city):?>
    <?php echo $city->cityname; ?>
  <?php endforeach;?>
<?php endforeach;?>

Buena suerte

respondido 08 nov., 11:22

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.