What is the best approach to calculate the percentage occurrence of values in a multidimensional array in PHP?
To calculate the percentage occurrence of values in a multidimensional array in PHP, you can iterate through the array and keep track of the count of each unique value. Then, you can calculate the percentage by dividing the count of each value by the total number of elements in the array and multiplying by 100.
<?php
function calculatePercentageOccurrence($array) {
$counts = array_count_values(array_merge(...$array));
$total = array_sum($counts);
$percentages = [];
foreach ($counts as $value => $count) {
$percentage = ($count / $total) * 100;
$percentages[$value] = $percentage;
}
return $percentages;
}
// Example usage
$multiArray = [[1, 2, 3], [1, 2, 4], [1, 3, 5]];
$percentages = calculatePercentageOccurrence($multiArray);
print_r($percentages);
?>