Hi everyone
I have an array, $list, like so
Array
(
[0] => Array
(
[siteid] => 1
[orderID] => 123456
[ClientID] => JOHNS
[ClientName] => John's Butchers
[SalesType] => A
[revenue] => Array
(
[0] => Nil
[1] => Nil
[2] => 100
)
)
[1] => Array
(
[siteid] => 1
[orderID] => 123457
[ClientID] => JOHNS
[ClientName] => John's Butchers
[SalesType] => A
[revenue] => Array
(
[0] => 200
[1] => Nil
[2] => Nil
)
)
[2] => Array
(
[siteid] => 2
[orderID] => 123890
[ClientID] => JOHNS
[ClientName] => John's Butchers
[SalesType] => B
[revenue] => Array
(
[0] => 300
[1] => Nil
[2] => Nil
)
)
[3] => Array
(
[siteid] => 1
[orderID] => 123234
[ClientID] => BILLS
[ClientName] => Bill's Bakers
[SalesType] => C
[revenue] => Array
(
[0] => Nil
[1] => 175
[2] => Nil
)
)
[4] => Array
(
[siteid] => 3
[orderID] => 123479
[ClientID] => TIMMYS
[ClientName] => Timmy's Fruit & Veg
[SalesType] => A
[revenue] => Array
(
[0] => 250
[1] => Nil
[2] => Nil
)
)
The revenue array represents 3 months of values.
I want to reduce the entire array to a new one containing just the ClientID, name and the revenue array. The rest of the data can be ignored. If the ClientID exists more than once, the revenue should be summed for each month.
I've done this a really long-hand way. Does anyone have a suggestion of how to approach this in a neater way? Here's my current code assuming the above array exists in the variable $list;
$totalarray = array();
foreach($list AS $orderdetails){
if (array_key_exists($orderdetails[ClientID], $totalarray)){ // this clientID is already in the new array
// update the revenue array, summing in the new values
$i=0;
foreach($orderdetails[revenue] AS $value){
$totalarray[$orderdetails[ClientID]][revenue][$i] = $totalarray[$orderdetails[ClientID]][revenue][$i] + $value;
$i++;
}
}
else{ // this clientID is not in the new array yet, add the values (and the client name)
$totalarray[$orderdetails[ClientID]][ClientName] = $orderdetails[ClientName];
$i = 0;
foreach($orderdetails[revenue] AS $value){
$totalarray[$orderdetails[ClientID]][revenue][$i] = $value;
$i++;
}
}
}
Result array:
Array
(
[JOHNS] => Array
(
[ClientName] => John's Butchers
[revenue] => Array
(
[0] => 500
[1] => Nil
[2] => 100
)
)
[BILLS] => Array
(
[ClientName] => Bill's Bakers
[revenue] => Array
(
[0] => Nil
[1] => 175
[2] => Nil
)
)
[TIMMYS] => Array
(
[ClientName] => Timmy's Fruit & Veg
[revenue] => Array
(
[0] => 250
[1] => Nil
[2] => Nil
)
)
)
Thanks for your help.