Jump to content

how to prevent appending same property twice in array in nested foreach


johnmerlino

Recommended Posts

Hey all,

 

I have two objects that contain object instances. I want to compare the properties of the instances and if the old_parent's property doesn't exist as one of the $new_parent's property, then I place the old_parent's property in an array called unneeded_ids. Problem is when I use nested foreach to loop through the instances of the two objects, despite old_parent having only one instance with a property id of 1, because it loops twice, the array gets two "1" values rather than just one:

 

public function update(){
		$vanity_url = new VanityUrl();
		$vanity_url->where('user_id',$this->current_user()->id)->get();

		$zones = $this->input->post('zones');
		$zone = new Zone();
		$zone->where_in('name', $zones)->get();

		$subcategory = new Category();
		$subcategory->where('id',$this->uri->segment(4))->get();

		$old_parents = new Category();
		$old_parents = $subcategory->related_category->get();

		$unneeded_ids = array(); 

		if(!$this->input->post('catupload')){
			if($subcategory->save($zone->all)){
				redirect("blogs/$vanity_url->url/categories"); 
			}
			else {
				echo "Error occurred. Please try again.";
			}
		}
		else {
			$new_parents = new Category();
			$controller = $this->input->post('catupload');
			$new_parents->where_in('controller',$controller)->get();

			foreach($new_parents as $new){ 
				foreach($old_parents as $old){
					if($new->id != $old->id){
							array_push($unneeded_ids, $old->id);
						}
				}
			}
			var_dump($unneeded_ids); 

		}
	}

 

The var_dump outputs:

array(4) { [0]=> int(126) [1]=> int(127) [2]=> int(126) [3]=> int(127) } 

but it should only output:

array(2) {[0]=> int(126) [1]=> int(127)}

That's because there's only one object instance of old_parent that has a property id value of 126 and the same for 127. The nested for each loop is causing it to iterate twice against the same object and sticking it into the array. How do I get desired result?

 

Thanks for response.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.