[Phpwm] updating an array
Rob Allen
rob at akrabat.com
Thu Oct 19 19:40:04 BST 2006
alan dunn wrote:
> in response to Rob here is the entire loop:
> there are a maximum of four products with varying quantities e1,q1, e2,
> q2, e3, q3, e4, q4
[snip]
> // loop through second array
> foreach ($secondarray as $key2 => $qty2){
> // comparing values in first array
> foreach ($prodarray as $key1 => $qty1){
> $match = 'f';
> if($key1 == $key2){
> //echo"key1=$key1 qty1= $qty1 key2=$key2 qty2 = $qty2
> tot = $tot<br>
> //prodarraykey1 = $prodarray[$key1]<br> ";
> $prodarray[$key1] = &$tot; // here we have tried to use the & notation
> $tot = $tot + $qty2;
> $match = 't';}
> // if there is no match add the product to prodarray
> } // end foreach prodarray
> // if there was no match add a new line to prodarray -- this
> bit works!
> if($match == 'f'){$prodarray[$key2] = $qty2; }
> } // end for each second array
> } // end else
>
$match will always be 'f' at the if($match == 'f') statement, unless you
happen to match key1 to key2 on the very last iteration through prodarray.
You should move the $match='f' statement to outside the
foreach($prodarray) loop. Also, set $match to false/true rather than the
characters t and f.
A much better way to handle that problem is to use in_array() rather
than the inner foreach loop. Something like:
// loop through second array
foreach ($secondarray as $key => $qty)
{
if(in_array($key, $prodarray))
{
$prodarray[$key] += $qty;
}
else
{
$prodarray[$key] = $qty;
}
}
Then you don't need to worry about $match at all and you save a PHP
loop, so the code will be quicker.
Regards,
Rob...
More information about the Phpwm
mailing list