I have an array representing connections between nodes.
Given a specific end node, I'd like to return a subset of the nodes that lead to this end node.
E.g. If my nodes definitions are "a-b", "a-c","c-e", "e-f", "e-k","k-z","q-z", "x-q" "k-m", "c-t" which represent the following:
and I'd like to see the path(s) leading to 'z', which are:
- a-c, c-e, e-k, k-z
- q-z, x-q
I have this PHP code:
<?php
$end = "z";
$items = array("a-b", "a-c", "c-e", "e-f", "e-k", "k-z", "q-z", "x-q", "k-m", "c-t");
$graph = getPre($items, $end);
print_r($graph); // This is what I want to populate
exit();
function getPre($array, $char) {
$predecessors = array_filter($array, function($line) use($char) {
return strpos(substr($line, 2, 1), $char) === FALSE ? FALSE : TRUE;
}
);
if (count($predecessors) == 0) {
return;
} else {
print_r($predecessors)."<br>";
echo "<br>";
foreach ($predecessors as $pre) {getPre($array, substr($pre, 0,1));}
}
}
?>
which outputs:
Array ( [5] => k-z [6] => q-z )
Array ( [4] => e-k )
Array ( [2] => c-e )
Array ( [1] => a-c )
Array ( [7] => x-q )
which at least is the correct nodes list, so I'm almost there.
Question: How do I have have the results returned in my $graph
array?
Somewhere I need to return $predecessors;
and have it merged with the previous results. I will also want to add functionality to be able to specify a start node, but I think that will just be an extra test in my recursive end test.