I want to restructure the array, and some of the solutions on stuckoverflow helped me make it βcorrectβ for level 1 elements, but you will notice that the array is n-level deep.
The restructure () method is not used recursively (it should be). He is probably mistaken, and has no idea how to do it right.
The children key says that there are children with the corresponding identifier, the parent key associates the element with the parent identifier.
class FilterMenu {
protected $tree = array();
static protected $structure = array();
public function __construct(array $tree)
{
$this->tree = $tree;
}
public function getStructure()
{
self::restructure($this->tree);
return self::$structure;
}
static public function restructure(array $structure)
{
foreach ($structure as $k => $v)
{
if (isset($v['parent']) and isset($v['children']) and count($v['children']) == 1)
{
self::$structure[$k] = current(array_keys($v['children']));
}
elseif (isset($v['children']))
{
$keys = array_keys($v['children']);
self::$structure[$k] = array_combine($keys, $keys);
}
else
{
self::$structure[$k] = $k;
}
}
}
}
$tree = array(
1 => array(
'parent' => 1
),
2 => array(
'parent' => 2,
'children' => array(
3 => array(
'parent' => 2
),
6 => array(
'parent' => 2,
'children' => array(
10 => array(
'parent' => 6,
'children' => array(
4 => array(
'parent' => 10
)
)
)
),
),
),
),
7 => array(
'parent' => 7,
'children' => array(
11 => array(
'parent' => 7
)
)
),
14 => array(
'parent' => 14,
'children' => array(
15 => array(
'parent' => 14,
),
16 => array(
'parent' => 14,
),
19 => array(
'parent' => 14,
),
20 => array(
'parent' => 14,
),
21 => array(
'parent' => 14,
),
)
)
);
$tree = new FilterMenu($tree);
echo '<pre>'.print_r($tree->getStructure(), true);
Actual result:
Array
(
[1] => 1
[2] => Array
(
[3] => 3
[6] => 6
)
[7] => 11
[14] => Array
(
[15] => 15
[16] => 16
[19] => 19
[20] => 20
[21] => 21
)
)
desired / expected result:
Array
(
[1] => 1
[2] => Array
(
[3] => 3
[6] => Array
(
[10] => 4
)
)
[7] => 11
[14] => Array
(
[15] => 15
[16] => 16
[19] => 19
[20] => 20
[21] => 21
)
)
Here is a link to a codeword that checks the class and array.
Any help is appreciated. Thank.