Changing an array while walking the array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
poemind
Forum Newbie
Posts: 3
Joined: Wed Jan 31, 2007 1:10 pm

Changing an array while walking the array?

Post by poemind »

Hi,

I'm having trouble figuring out how to change an array's elements while walking that array.

What I have tried is this.

Code: Select all

foreach( $lead_stage_arr as $stage ){			
	$query = "SELECT COUNT(*) count FROM leads, leads_cstm WHERE assigned_user_id='".$current_user->id."' AND ".$stage['name']."='1'"  ;
	$result = $lead->db->query($query);	
	$row=$lead->db->fetchByAssoc($result);			
	$stage['value'] = $row['count']; //	set array for new_c		
}		
I have read that this simply makes a copy of $lead_stage_arr in $stage and as such will not affect the former.

I've also read something about placing & before $stage as such: &stage.

But that did not work. Any ideas how to do this. I will keep looking but thanks in advance for any help that you can give me.

poemind.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$stage is a copy, so under most circumstances we would use the key (provided by foreach) to dig back into the source ($lead_stage_arr).

However, I think your code could be optimized by using an IN clause and group by. What is $stage['name']?
User avatar
poemind
Forum Newbie
Posts: 3
Joined: Wed Jan 31, 2007 1:10 pm

Should have mentioned...

Post by poemind »

that $lead_stage_arr is a multidimensional array.

The structure of which is:

Code: Select all

$lead_stage_arr[0] = array( 
        'name'=> 'new_c',
	'label'=>'New',
	'value'=> 0
);
This being just the first element in the array. The only thing that I need to change is the 'value' field. That is what I'm querying with the COUNT(*) from the MySQL query. The 'name' is the name of the field in the db.

That might change the equation somewhat, huh? Thanks for your rapid response! Very impressive board!

poemind.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

As I said before, use the key given by foreach to dig back into $lead_stage_arr.

Your code appears to be implicitly joining two tables. Without a constraint, the result is exponential in nature.
User avatar
poemind
Forum Newbie
Posts: 3
Joined: Wed Jan 31, 2007 1:10 pm

THANKS!!!

Post by poemind »

Many thanks! That worked like a charm. I have truly learned something today!

I will be using these forums often!

Quick response and good answers. Can't beat that!

Peace

poemind
Post Reply