I have a question like this:
Create a function that takes in a nested array and an element and returns the frequency of that element by nested level.
Example:
freqCount([1, 4, 4, [1, 1, [1, 2, 1, 1]]], 1) ➞ [[0, 1], [1, 2], [2,3]] // The array has one 1 at level 0, 2 1's at level 1, and 3 1's at level 2.
So I have to use recursion since we don't know how many levels there are. I am getting the right number of occurrences of the $el passed but not the right level of depth because $depth keeps getting reset on every new call of recurse();
Here is the basic code:
<?php
function freqCount($arr, $el) {
recurse($arr, $el);
}
function recurse($a, $e) {
$counter = 0;
$depth = 0;
$result = [];
foreach($a as $k => $v) {
if(!is_array($v) && $v === $e) {
$counter++;
$result[$depth] = $counter;
} elseif(is_array($v)) {
$depth++;
recurse($v, $e);
} else {
continue;
}
}
echo "<pre>";
print_r($result);
}
Outputs:
Array
(
[0] => 3 // Should be [2] => 3
)
Array
(
[0] => 2 // Should be [1] => 2
)
Array
(
[0] => 1
)
static $depth = 0;also I think you'll need to decrement it somewhere also.staticdoes keep track of the depth, thanks! Why would I need to decrement it? Here's the question: edabit.com/challenge/F96gXX2c8BvKnYiZ8