Skip to content

Commit e6270e1

Browse files
committed
Added pack method and updated unpack documentation
1 parent 8466678 commit e6270e1

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/Arr.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,23 @@ public static function setNestedElement(array $array, $keys, $value): array
163163
return $result;
164164
}
165165

166+
/**
167+
* Converts map of keys concatenated by dot and corresponding values to multidimensional array
168+
*
169+
* @param array $array
170+
* @return array
171+
*/
172+
public static function pack(array $array): array
173+
{
174+
$result = [];
175+
176+
foreach ($array as $key => $value) {
177+
$result = self::setNestedElement($result, $key, $value);
178+
}
179+
180+
return $result;
181+
}
182+
166183
/**
167184
* Converts multidimensional array to map of keys concatenated by dot and corresponding values
168185
*

test/ArrTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,37 @@ public function testSetNestedElement()
112112
$this->assertSame([[[[]]]], Arr::setNestedElement([], '[].[].[]', []));
113113
}
114114

115+
public function testPack()
116+
{
117+
$result = [
118+
'key1' => [
119+
'key2' => [
120+
'key3' => ['test', 'test2'],
121+
'key4' => 'test3'
122+
],
123+
1 => ['a' => 'b', 'c'],
124+
],
125+
2 => [3 => 4, 5 => 6],
126+
4 => 56
127+
];
128+
$input = [
129+
'key1.key2.key3.0' => 'test',
130+
'key1.key2.key3.1' => 'test2',
131+
'key1.key2.key4' => 'test3',
132+
'key1.1.a' => 'b',
133+
'key1.1.0' => 'c',
134+
'2.3' => 4,
135+
'2.5' => 6,
136+
4 => 56,
137+
138+
];
139+
$array2 = [1, 2, 3, 4, 5];
140+
141+
$this->assertSame($result, Arr::pack($input));
142+
$this->assertSame($array2, Arr::pack($array2));
143+
$this->assertSame($result, Arr::pack(Arr::unpack($result)));
144+
}
145+
115146
public function testUnpack()
116147
{
117148
$array = [

0 commit comments

Comments
 (0)