1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SimpleArrayLibrary\Categories; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
trait Counters |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Counts maximum array depth recursively |
11
|
|
|
* |
12
|
|
|
* @param array $array |
13
|
|
|
* |
14
|
|
|
* @return int |
15
|
|
|
*/ |
16
|
|
|
public static function countMaxDepth(array $array) |
17
|
|
|
{ |
18
|
|
|
$maxDepth = 1; |
19
|
|
|
foreach ($array as $element) { |
20
|
|
|
$depth = 1; |
21
|
|
|
if (is_array($element)) { |
22
|
|
|
$depth += self::countMaxDepth($element); |
23
|
|
|
} |
24
|
|
|
if ($depth > $maxDepth) $maxDepth = $depth; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return $maxDepth; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Counts maximum array depth iteratively |
32
|
|
|
* |
33
|
|
|
* @param array $array |
34
|
|
|
* |
35
|
|
|
* @return int |
36
|
|
|
*/ |
37
|
|
|
public static function countMaxDepthIterative(array $array) |
38
|
|
|
{ |
39
|
|
|
$copy = $array; |
40
|
|
|
$maxDepth = 1; |
41
|
|
|
|
42
|
|
|
foreach ($copy as $element) { |
43
|
|
|
$depth = 1; |
44
|
|
|
while (!empty($element)) { |
45
|
|
|
if (is_array($element)) { |
46
|
|
|
++$depth; |
47
|
|
|
$tmp = array_shift($element); |
48
|
|
|
if (is_array($tmp)) { |
49
|
|
|
array_push($element, array_shift($tmp)); |
50
|
|
|
} |
51
|
|
|
} else { |
52
|
|
|
break; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
if ($depth > $maxDepth) { |
56
|
|
|
$maxDepth = $depth; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $maxDepth; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Counts maximum array depth |
65
|
|
|
* |
66
|
|
|
* @param mixed $potentialArray |
67
|
|
|
* @param int $depth |
68
|
|
|
* |
69
|
|
|
* @return int |
70
|
|
|
* @throws InvalidArgumentException |
71
|
|
|
*/ |
72
|
|
|
public static function countMinDepth($potentialArray, $depth = 0) |
73
|
|
|
{ |
74
|
|
|
// validation, must be positive int or 0 |
75
|
|
|
if (!self::isLogicallyCastableToInt($depth)) { |
76
|
|
|
throw new InvalidArgumentException('Depth parameter must be non-negative integer'); |
77
|
|
|
} |
78
|
|
|
if ($depth < 0) { |
79
|
|
|
throw new InvalidArgumentException('Depth parameter must be non-negative integer'); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$return = $depth; |
83
|
|
|
if (is_array($potentialArray)) { |
84
|
|
|
$return++; |
85
|
|
|
$childrenDepths = array(); |
86
|
|
|
foreach ($potentialArray as $element) { |
87
|
|
|
$childrenDepths[] = self::countMinDepth($element, $return); |
88
|
|
|
} |
89
|
|
|
$return = empty($childrenDepths) ? $return : min($childrenDepths); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return $return; |
93
|
|
|
} |
94
|
|
|
} |