Search code examples
phparrayscodeignitercodeigniter-2associative-array

Only last element stores in array in CI


I'm using array in ci . whenever i store i can get only the last elements ! other elements are overwrite.

this is my code

$table="wp_term_taxonomy";     
$data=array();
$this->db->where('taxonomy','Geographical');
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
  foreach ($query->result() as $value) {
  $terms_id=$value->term_id;
  $table2="wp_terms";
  $this->db->where('term_id',$terms_id);
  $query2 = $this->db->get($table2);
  if ($query2->num_rows() > 0)
  {
     foreach ($query2->result() as $value2) {
        $data['name']=$value2->name;
        $data['id']=$value2->term_id;
        }
    }
  }
 }


var_dump($data);
return $data;
}

i get only the last element in $data array


Solution

  • You are overriding values. Try it like this:

    foreach ($query2->result() as $value2) {
        $data[]=array('name' => $value2->name, 'id' => $value2->term_id);
    }