-
Notifications
You must be signed in to change notification settings - Fork 0
/
Set.php
81 lines (71 loc) · 1.36 KB
/
Set.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Templater;
class Set
{
public static function setObject($array): object
{
if (is_array($array))
{
$object = new \stdClass();
foreach ($array as $key => $value)
{
if (is_array($value))
{
$value = self::setObject($value);
}
$object->{$key} = $value;
}
return $object;
}
}
public static function setArray($object): array
{
if (isset($object))
{
foreach ($object as $key => $val)
{
$p[$key] = $val;
}
}
return $p;
}
//Thanks to https://stackoverflow.com/a/14706302
public static function dotNotation(array $a, $path, $default = null)
{
$current = $a;
$p = strtok($path, '.');
while ($p !== false)
{
if (!isset($current[$p]))
{
return $default;
}
$current = $current[$p];
$p = strtok('.');
}
return $current;
}
public static function flattenToMultiDimensional(array $array, $delimiter = '.')
{
$result = [];
foreach ($array as $notations => $value)
{
// extract keys
$keys = explode($delimiter, $notations);
// reverse keys for assignments
$keys = array_reverse($keys);
// set initial value
$lastVal = $value;
foreach ($keys as $key)
{
// wrap value with key over each iteration
$lastVal = [
$key => $lastVal
];
}
// merge result
$result = array_merge_recursive($result, $lastVal);
}
return $result;
}
}