Jump to content

foreach with in a foreach, bad idea?


Iluvatar+

Recommended Posts

Alright guys,

 

Just wondering if anyone could give me a bit of advice. I am using a foreach with in a foreach to insert records in a table. This is the only solution i could come up up with for the nature of this function. I will try and explain as simple as possible...

 

I needed to insert a set of records for each department, each set of records are based on how many franchise there is (with in a table).

 

 

This is my code which is working fine, but i want to make sure it's the best way to go about this. (keep in mind i am using cakephp)

 

<?php
    //...

                                                        $this->loadmodel('Userdepartmentlink');

						$this->loadmodel('Department'); /**/ $departments = $this->Department->find('all');

						foreach($departments as $departments){

							$department_id = $departments['Department']['id'];
							$this->loadmodel('Franchise');  /**/ $franchises = $this->Franchise->find('all');
							foreach($franchises as $franchises){

									$sets = array(
												array(
													  'user_id'=>'7',
													  'department_id'=>$department_id,
													  'franchise_id'=>$franchises['Franchise']['id']
													  ),
										   );


									if($this->Userdepartmentlink->saveAll($sets)) {
										echo "saved";
									}
									else {
										echo "doesnt work";
									}

							}




?>

Link to comment
https://forums.phpfreaks.com/topic/258995-foreach-with-in-a-foreach-bad-idea/
Share on other sites

Do you always need all fields for your purposes? NO its a waste of memory, start using $find(,array('fields'=>'') for better efficacy

 

foreach($departments as $departments) and foreach($franchises as $franchises)? NO

 

Do not load the same model on each iteration of the foreach loop.  Waste of time/memory

 

Stop doing this single line nonsense "$this->loadmodel('Department'); /**/ $departments = $this->Department->find('all');"

Break up the code by putting it on another line, use vertical spacing to group similar code.

 

Error out or make use of a logger, echo'ing is only good for debugging.

 

Document what you're doing with this function, in a month will you really understand what this does?

 

As for your main concern, you need to reread the Models documentation, especially the section concerning associations.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.