forked from Ontraport/Backend-Test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertContainer.php
More file actions
70 lines (60 loc) · 1.84 KB
/
ConvertContainer.php
File metadata and controls
70 lines (60 loc) · 1.84 KB
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
<?php
class ConvertContainer
{
/**
* Pass multi-dimensional container to get dimensional associative array
* @param array $array
* @param string $parentKey
* @param array $result
* @return array
*/
public function convert($array, $parentKey = '', $result = []) {
$parentKey = $parentKey . ($parentKey == '' ? '' : '/');
if(empty($array)){
return [];
}
foreach ($array as $key => $value) {
// if value is also array check it recursively to build final array
if(is_array($value)) {
$result = $this->convert($value, $parentKey . $key, $result);
} else {
//we reached end or array path lets add $parentKey, $key and value to the result
$result[$parentKey . $key] = $value;
}
}
return $result;
}
/**
* Convert associative array into multi-dimensional container
* @param array $array
* @return array
*/
public function reverseConvert($array) {
$result = [];
if(empty($array)){
return [];
}
foreach ($array as $key => $value) {
$keysArr = (explode('/', $key));
//build multi dimensional array from each element of array
$tmpArr = $this->buildMultiDimensionalArray($keysArr, $value);
$result = array_replace_recursive($result, $tmpArr);
}
return $result;
}
/**
* @param array $keys
* @param string $value
* @return array
*/
public function buildMultiDimensionalArray($keys, $value) {
$result = $value;
$keys = array_reverse($keys);
foreach ($keys as $key) {
$temp = $result;
$result = [];
$result[$key] = $temp;
}
return $result;
}
}