I try to figure out how to handle my array to do "some math" with its values. The array looks similar to this:
Array
(
[0] => Array
(
[person1] => 71
[person2] => 49
[person3] => 15
)
[1] => Array
(
[person1] => 56
[person3] => 43
[person4] => 21
[person5] => 9
[person6] => 7
)
...
)
Each value should be divided by the total amount: The first value should therefore be 71/(71+49+15)=0.526 or 52.6%.
The values should be rounded to 3 decimal places. Can someone provide me with an array_walk (or foreach) function? I just can't figure it out.
The final array should look like this:
Array
(
[0] => Array
(
[person1] => 52.6%
[person2] => 36.3%
[person3] => 11.1%
)
[1] => Array
(
[person1] => 41.2%
[person3] => 31.6%
[person4] => 15.4%
[person5] => 6.6%
[person6] => 5.1%
)
...
)
Thanks!
Assuming
$arr
is your initial array, and$new_arr
will be the new one.The array_walk() variation:
Note that array_walk() modifies the original array; if you want that to remain unchanged, use array_map() instead
You can use
array_sum()
to add up those values, then calculate your ratio/percentage for each and add to a new array:Edit: here's a demo