Page 1 of 1

Changing an array while walking the array?

Posted: Wed Jan 31, 2007 1:26 pm
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.

Posted: Wed Jan 31, 2007 1:34 pm
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']?

Should have mentioned...

Posted: Wed Jan 31, 2007 1:42 pm
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.

Posted: Wed Jan 31, 2007 2:07 pm
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.

THANKS!!!

Posted: Wed Jan 31, 2007 2:19 pm
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