CodeIgniter Forums
Assigning new elements to an associated array witin a foreach - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Assigning new elements to an associated array witin a foreach (/showthread.php?tid=23678)



Assigning new elements to an associated array witin a foreach - El Forum - 10-19-2009

[eluser]Tim Reynolds[/eluser]
I am having problems with assigning a new element to an array during a foreach loop.

While echoing the alias of the array position inside the foreach the new element seems to have been created and populated correctly. When you print the array outside the loop it does not contain the new fields. The code is part of a big method but the snippet is included,

Code:
$this->CI->template['navigation'] = $this->CI->page->getNav(0);
foreach($this->CI->template['navigation'] as $nav){
$subnav = $this->CI->page->getSubNav($nav['path']);
$nav['subnav'] = $subnav;
}

Is this the correct method of performing this operation? I can post more code/debug info if needed.

Thanks


Assigning new elements to an associated array witin a foreach - El Forum - 10-19-2009

[eluser]überfuzz[/eluser]
Could you post the array before altering it and the array you're aiming for.


Assigning new elements to an associated array witin a foreach - El Forum - 10-19-2009

[eluser]Krzemo[/eluser]
Code:
$nav['subnav'][] = $subnav;
???


Assigning new elements to an associated array witin a foreach - El Forum - 10-19-2009

[eluser]mattpointblank[/eluser]
Cshamoh is right, you're just overwriting the same array index each time, so you should end up with just the final item in the $nav array in your subnav.