Reputation: 31
I have the following multidimensional array $array:
Array
(
[criteria] => default
[name] => default
[data] => Array
(
[0] => Array
(
[criteria] => test1
[name] => test1_name
[data] => Array
(
[0] => Array
(
[criteria] => test2
[name] => test2_name
[data] => Array
(
)
)
[1] => Array
(
[criteria] => test3
[name] => test3_name
[data] => Array
(
)
)
)
)
[1] => Array
(
[criteria] => test4
[name] => test4_name
[data] => Array
(
)
)
)
)
I need to extract the name of each node($array['data']) with the criteria and the criteria of all parent nodes before it. Something like:
Array
(
Array
(
[name] => default
[criteria] =>
array(
[0] => default
)
)
Array
(
[name] => test1
[criteria] => array
(
[0] => default
[1] => test1
)
)
Array
(
[name] => test2
[criteria] => array
(
[0] => default
[1] => test1
[2] => test2
)
)
Array
(
[name] => test3
[criteria] => array
(
[0] => default
[1] => test1
[2] => test3
)
)
Array
(
[name] => test4
[criteria] => array
(
[0] => default
[1] => test4
)
)
)
Note that the name field of each array in this situation will never have the name duplicated anywhere.
Upvotes: 1
Views: 55
Reputation: 809
$a = array
(
'criteria' => 'default',
'name' => 'default',
'data' => array
(
'0' => Array
(
'criteria' => 'test1',
'name' => 'test1_name',
'data' => array
(
'0' => array
(
'criteria' => 'test2',
'name' => 'test2_name',
'data' => array
(
)
),
'1' => array
(
'criteria' => 'test3',
'name' => 'test3_name',
'data' => array
(
)
)
)
),
'1' => array
(
'criteria' => 'test4',
'name' => 'test4_name',
'data' => array
(
)
)
)
);
function buildHelper($nodeList, $currentPath, &$path) {
foreach($nodeList as $node) {
// add creteria to current path
array_push($currentPath, $node['criteria']);
array_push($path, array('name' => $node['name'], 'citeria' => $currentPath));
// go throught child list
if (is_array($node['data']))
buildHelper($node['data'], $currentPath, $path);
// remove from current path
array_pop($currentPath);
}
}
function build($node) {
// always from root node
$currentPath = array($node['criteria']);
$result = array();
array_push($result, array('name' => $node['name'], 'citeria' => $currentPath));
if (is_array($node['data']))
buildHelper($node['data'], $currentPath, $result);
return $result;
}
print_r(build($a));
Upvotes: 1