Jump to content

[SOLVED] Consolidating an array while adding another's values...


Praetorian46

Recommended Posts

OK what I'm am trying to do is basically remove duplicate entries in one array.  Then where ever there was a duplicate value.  So if ArrayID(3) was a duplicate of ArrayID(0)  then I want to add ArrayAmount(3) and ArrayAmount(0) together...  but I want this to be able to work at a large scale.  there may be 1000 values in the array and 50 IDs are the same. Here is what I've come up with so far but I'm getting an error.  The code is probably messy since I'm fairly new to PHP.

<?php
//$JI is an array with allot of "Job IDs" in it
//$BA is an array with allot of "Billing Amounts" in it
//Both arrays will always be the same length

$NewBA=array('');
$NewJI=array('');
for($x=0; $x <=(count($JI)-1); $x++){
   for($y=0; $y<=(count($JI)-1); $y++){
      if($JI($x)==$JI($y) and $x!=$y and $y>$x){
         if($NewBA($x)==0)$NewBA($x)=$BA($x);  //*See ERROR below
         $NewBA($x)+=$BA($y);
         $NewJI($x)=$JI($x);
      }
   }
}
?>

Here is the error I get

ERROR:
PHP Fatal error:  Can't use function return value in write context

 

??? I'm not sure where to go from here since the code errors out before I can even debug it.

Any help would be appreciated thank you very much.

-Cody

Well, thew first problem I see (which is probably causing your error) is that you are not referencing the array's correctly.

$NewBA($x) //Incorrect format
$NewBA[$x] //Correct format

 

That being said, I think there is a more efficient solution:

 

<?php

$array_sums = array();

foreach ($ArrayID as $key => $id_value) {
    $array_sums[$id_value] += $ArrayAmount[$key];
}

?>

 

When that completes you will hav a new array ($array_sums) with the following format:

 

array (
    'id1' => summedvaluesforid1,
    'id2' => summedvaluesforid2,
    'id3' => summedvaluesforid3
    .
    .
    .

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.