blob: 8845ef1c4dd6a571bc67d92096d3c4d1fdc60d0a (
plain)
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
82
83
84
85
86
87
88
89
|
<?php
/**
* Support for JSON message file format.
*
* @file
* @author Niklas Laxström
* @license GPL-2.0+
* @since 2016.01
*/
class ArrayFlattener {
protected $sep;
public function __construct( $sep = '.' ) {
$this->sep = $sep;
}
/**
* Flattens multidimensional array.
*
* @param array $unflat It's an array.
* @return array
*/
public function flatten( array $unflat ) {
$flat = array();
foreach ( $unflat as $key => $value ) {
if ( !is_array( $value ) ) {
$flat[$key] = $value;
continue;
}
// Placeholder for special plural processing
$temp = array();
foreach ( $value as $subKey => $subValue ) {
$newKey = "$key{$this->sep}$subKey";
$temp[$newKey] = $subValue;
}
$flat += $this->flatten( $temp );
// Can as well keep only one copy around.
unset( $unflat[$key] );
}
return $flat;
}
/**
* Performs the reverse operation of flatten.
*
* @param array $flat It's an array
* @return array
*/
public function unflatten( $flat ) {
$unflat = array();
foreach ( $flat as $key => $value ) {
$path = explode( $this->sep, $key );
if ( count( $path ) === 1 ) {
$unflat[$key] = $value;
continue;
}
$pointer = &$unflat;
do {
/// Extract the level and make sure it exists.
$level = array_shift( $path );
if ( !isset( $pointer[$level] ) ) {
$pointer[$level] = array();
}
/// Update the pointer to the new reference.
$tmpPointer = &$pointer[$level];
unset( $pointer );
$pointer = &$tmpPointer;
unset( $tmpPointer );
/// If next level is the last, add it into the array.
if ( count( $path ) === 1 ) {
$lastKey = array_shift( $path );
$pointer[$lastKey] = $value;
}
} while ( count( $path ) );
}
return $unflat;
}
}
|