forked from zxzzxxzx/test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test2.php
92 lines (85 loc) · 2.21 KB
/
test2.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
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Написать функцию которая из этого массива
*/
$data1 = [
'parent.child.field' => 1,
'parent.child.field2' => 2,
'parent2.child.name' => 'test',
'parent2.child2.name' => 'test',
'parent2.child2.position' => 10,
'parent3.child3.position' => 10,
];
//сделает такой и наоборот
$data = [
'parent' => [
'child' => [
'field' => 1,
'field2' => 2,
]
],
'parent2' => [
'child' => [
'name' => 'test'
],
'child2' => [
'name' => 'test',
'position' => 10
]
],
'parent3' => [
'child3' => [
'position' => 10
]
],
];
function convertArray($array) {
$resultArray = [];
foreach ($array as $key => $value) {
if(strpos($key, '.')!==false) {
$chunks = array_reverse(explode('.',$key));
$newArray = [];
foreach ($chunks as $chunk) {
if(empty($newArray)) {
$newArray[$chunk] = $value;
} else {
$newArray[$chunk] = $newArray;
unset($newArray[$previusChunk]);
}
$previusChunk = $chunk;
}
$resultArray = array_merge_recursive($resultArray,$newArray);
} else {
while(!empty($value)) {
$newElement = convertElement2Dot($value,[$key]);
if($newElement !== NULL)
$resultArray[] = $newElement;
}
}
}
return $resultArray;
}
function convertElement2Dot(&$array,$dotKey) {
if(is_array($array))
{
foreach($array as $key=>&$arrayElement)
{
if(empty($arrayElement)) {
unset($array[$key]);
return;
}
$dotKey[] = $key;
if(is_array($arrayElement))
{
return get($arrayElement,$dotKey);
}
else
{
unset($array[$key]);
return [implode('.',$dotKey)=>$arrayElement];
}
}
} else {
return [$dotKey => $array];
}
}