bigbobr
bigbobr

Reputation: 355

Return in recursive function php

I've got a little problem with recursive function output. Here's the code:

function getTemplate($id) {
    global $templates;
    $arr = $templates[$id-1];
    if($arr['parentId'] != 0) {
        $arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
    }
    return $arr['text']; 
}

The problem is that that function returns a value on each iteration like this:

file.exe
category / file.exe
root / category / file.exe

And I need only the last string which resembles full path. Any suggestions?

//UPD: done, the problem was with the dot in $arr['text'] .= str_replace

Upvotes: 0

Views: 197

Answers (3)

asarfraz
asarfraz

Reputation: 518

Try this please. I know its using global variable but I think this should work

$arrGlobal = array();

function getTemplate($id) {
    global $templates;
    global $arrGlobal;

    $arr = $templates[$id-1];
    if($arr['parentId'] != 0) {
       array_push($arrGlobal, getTemplate($arr['parentId']));
    }
    return $arr['text'];
}

$arrGlobal = array_reverse($arrGlobal);

echo implode('/',$arrGlobal);  

Upvotes: 1

AlexP
AlexP

Reputation: 9857

Give this a try:

function getTemplate($id, array $templates = array())
{
  $index = $id - 1;
  if (isset($templates[$index])) {
    $template = $templates[$index];
    if (isset($template['parentId']) && $template['parentId'] != 0) {
      $parent = getTemplate($template['parentId'], $templates);
      $template['text'] .= str_replace($template['attr'], $template['text'], $parent);
    }
    return $template['text'];
  }
  return '';
}

$test = getTemplate(123, $templates);

echo $test;

Upvotes: 0

Santosh Pradhan
Santosh Pradhan

Reputation: 149

Try this,

function getTemplate($id) {
    global $templates;
    $arr = $templates[$id-1];
    if($arr['parentId'] != 0) {
    return $arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
    }
}

Upvotes: 0

Related Questions