Created
September 19, 2017 13:59
-
-
Save u-mulder/cbd66b7256f1e6c2ad1f51cf1869667e to your computer and use it in GitHub Desktop.
ADV test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* test1.php */ | |
$x = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];; | |
$x = array_reduce( | |
$x, | |
function ($t, $v) { | |
$prev = $t; | |
$t = []; | |
$t[$v] = $prev; | |
return $t; | |
}, | |
'' | |
); | |
echo'<pre>',print_r($x),'</pre>'; | |
/* test2.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, | |
]; | |
$new_arr = []; | |
foreach ($data1 as $k => $v) { | |
$parts = explode('.', $k); | |
$end = sizeof($parts) - 1; | |
$cur_item = &$new_arr; | |
foreach ($parts as $part_key => $part_index) { | |
if (!isset($cur_item[$part_index])) { | |
$cur_item[$part_index] = []; | |
} | |
$cur_item = &$cur_item[$part_index]; | |
if ($part_key == $end) { | |
$cur_item = $v; | |
} | |
} | |
} | |
echo'<pre>',print_r($new_arr),'</pre>'; | |
$data = [ | |
'parent' => [ | |
'child' => [ | |
'field' => 1, | |
'field2' => 2, | |
] | |
], | |
'parent2' => [ | |
'child' => [ | |
'name' => 'test' | |
], | |
'child2' => [ | |
'name' => 'test', | |
'position' => 10 | |
] | |
], | |
'parent3' => [ | |
'child3' => [ | |
'position' => 10 | |
] | |
], | |
]; | |
$new_data = []; | |
foreach ($data as $k => $item) { | |
$path = $k; | |
restorePath($new_data, $path, $item); | |
} | |
function restorePath(&$new_data, $path, $el) | |
{ | |
if (is_array($el)) { | |
foreach ($el as $k => $v) { | |
restorePath($new_data, $path . '.' . $k, $v); | |
} | |
} else { | |
$new_data[$path] = $el; | |
} | |
} | |
echo'<pre>',print_r($new_data),'</pre>'; | |
/** | |
* И да, на стековерфлоу я закрыл несколько дубликатов подобных вопросов) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment