Reputation: 55
i have an array input like this ..
Array
(
[0] => Array
(
[0] => 42
)
[**42**] => Array
(
[0] => 12
[1] => 14
)
[**14**] => Array
(
[0] => 317
)
[317] => Array
(
[0] => 319
)
[**12**] => Array
(
[0] => 306
[1] => 307
)
[307] => Array
(
[0] => 311
)
[306] => Array
(
[0] => 309
)
)
and i want to get result array like bellow :
$paths[]=array(42,12,306,309);
$paths[]=array(42,12,307,311);
$paths[]=array(42,14,317,319);
see array input
like this..
and output array insert into $paths
$paths[0]=array(42,12,306,309);
$paths[1]=array(42,12,307,311);
$paths[2]=array(42,14,317,319);
Upvotes: 0
Views: 1463
Reputation: 77024
This should do the trick:
function getpaths($arr, $node = 0){
$path = array();
foreach($arr[$node] as $next){
if(isset($arr[$next])){
$p = getpaths($arr, $next);
foreach($p as $q){
$path[] = array_merge(array($next), $q);
}
}else{
$path[] = array($next);
}
}
return $path;
}
Invoke as $path = getpaths($arr);
Upvotes: 2
Reputation: 55
this is coding by Mark E, and i add one line coding to solve "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes)"
like this...
function getpaths($arr, $node = 0){
$path = array();
foreach($arr[$node] as $next){
if(isset($arr[$next])){
$node = $next;// adding by me
$p = getpaths($arr, $node);
foreach($p as $q){
$path[] = array_merge(array($next), $q);
}
}else{
$path[] = array($next);
}
}
return $path;
}
thanks Mark E
Upvotes: 0