I have this difficult task (for me at least).
This is abstract question, mathematical i’d say.
Let’s assume I have 2 inputs:
- a keyword (string)
- a number (deepness level)
and submit button.
This keyword returns me 8 other keywords from a database that are similar to this string.
And for each of that 8 keywords I need to call same function that will return me another 8 similar keywords of all these 8 strings I have already returned.
Here comes the “level” number. I need to go deeper inside every of returned string depending on level number I entered.
For example: If the level number is 2, then we will call the function 9 times. First time for the original keyword, and 8 times for each returned keyword.
If the level number is 3, then the function will be called 73 times. Like in the previous example, but plus for another 8 keywords we have returned. I think there will be a couple of loops inside loops, but can’t figure it out by myself. Will appreciate your suggestions.
Here’s the main code that I have wrote which is probably unsufficient:
$keywords = preg_split('/$\R?^/m', trim($_POST['keyword']));
$keywords = array_map('trim', $keywords);
$level = $_POST['level'];
if (!$level || $level < 2) {
echo '<b>Level was either 1 or null</b>';
}
foreach ($keywords as $keyword) {
$results = getResults($keyword);
if ($level && $results) {
for ($i = 0; $i < sizeof($results); $i++) {
$results1 = getResults($results[$i]);
for ($j = 0; $j < $level; $j++) {
$results1 = getResults($results1[$i])
}
}
}
}
The output should be something like this:
1->
2
->
3
3
3
3
3
3
3
3
2->
2->
2->
2->
You need to understand what
recursionmeans and how you can use it in your code. Basically you need to call the same function inside itself, n times where n is the deepness level of your request.Start with some little examples like Fibonacci series, and you will find the way to implement your function.
All is based on a condition
($deepness > 0).Here’s a little suggestion (in pseudocode) based on what I understood.