Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ADV test
<?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