php array_count_values multidimensional
In PHP, the array_count_values()
function is used to count the number of occurrences of all values in an array. However, this function only works for single-dimensional arrays and cannot directly count occurrences in multidimensional arrays.
To count the occurrences in a multidimensional array, you need to implement your own custom logic. One way to achieve this is by using nested loops and an associative array to store the counts.
Here’s an example:
<?php $array = array( array("apple", "banana", "apple"), array("orange", "apple", "banana"), array("apple", "orange", "banana") ); $result = array(); foreach ($array as $subArray) { foreach ($subArray as $value) { if (isset($result[$value])) { $result[$value]++; } else { $result[$value] = 1; } } } print_r($result); ?>
In this example, we have a multidimensional array with fruits. We initialize an empty $result
array to store the counts. Then, we iterate over each sub-array and within each sub-array, we iterate over each value. We check if the value already exists as a key in $result
. If it does, we increment the count by 1. Otherwise, we set the count to 1.
Finally, we use the print_r()
function to display the count of occurrences for each value in the multidimensional array.
The output of this code will be:
Array ( [apple] => 4 [banana] => 3 [orange] => 2 )
In this example, “apple” appears 4 times, “banana” appears 3 times, and “orange” appears 2 times in the given multidimensional array.
- Property ‘subscribe’ does not exist on type ‘void’.
- Paramiko check if directory exists
- Prettier if else new line
- Pydoc recursive
- Package ‘chromium’ has no installation candidate
- Publishing to tomcat v9.0 server at localhost
- Parser error message: the codedom provider type “microsoft.codedom.providers.dotnetcompilerplatform.csharpcodeprovider, microsoft.codedom.providers.dotnetcompilerplatform, version=2.0.1.0, culture=neutral, publickeytoken=31bf3856ad364e35” could not be located.
- Php add key value to json object