Hey guys, I'm having a bit of a problem with my template engine I'm bulding. I'll explain what it's doing right, and what it's doing wrong.

Take this sample .tpl HTML block
Code HTML4Strict:
<!-- Start Name //-->
<p>My name is {name} and I am {years} years old.</p>
<!-- End Name //-->

I assign it to my template object like this.

Code PHP:
$tpl->assignBlock(
    'Name',
    array(
        'name' => 'scott',
        'years' => 22
    )
);
 
$tpl->assignBlock(
    'Name',
    array(
        'name' => 'jim',
        'years' => 75
    )
);
 
$tpl->assignBlock(
    'Name',
    array(
        'name' => 'ann',
        'years' => 40
    )
);

Here's my template objects assignBlock() method:

Code PHP:
public function assignBlock($block, $values)
{
	$this->_blocks[$block][] = $values;
}

Then, in my template display() method, the following code will render the single HTML .tpl block into however many it needs.

Code PHP:
//replace blocks
foreach ($this->_blocks AS $block => $blockValues)
{	
	//get block
	$block = preg_match("/<!-- Start $block \/\/-->(.+?)<!-- End $block \/\/-->/ism", $tpl, $matches);
	$block = $matches[1];
 
	//new block for each iteration
	$newBlocks = array();
	foreach ($blockValues AS $blockValue)
	{
		$newBlock = $block;
		foreach ($blockValue AS $key => $value)
		{
			$newBlock = str_replace('{' . $key . '}', $value, $newBlock);
		}
 
		//save block
		$newBlocks[] = $newBlock;
	}
 
	//implode blocks back to string
	$newBlock = implode("\n", $newBlocks);
 
	//replace original block with replaced looped block
	$tpl = str_replace($block, $newBlock, $tpl);
}

That turns my single .tpl HTML block into:

Code HTML4Strict:
<p>My name is scott and I am 22 years old.</p>
<p>My name is jim and I am 75 years old.</p>
<p>My name is ann and I am 40 years old.</p>

All of the above works fine, I just wanted to show an example of what I'm doing.

My problem comes when I want to have nested template blocks, like the following:

Code HTML4Strict:
<!-- Start Category //-->
<tr>
	<td colspan="4" class="cat_name">{cat_name}</td>
</tr>
<tr>
	<td width="60%" class="titletext">{L_FORUM}</td>
	<td width="10%" class="titletext">{L_TOPICS}</td>
	<td width="10%" class="titletext">{L_POSTS}</td>
	<td width="20%" class="titletext">{L_LAST_POST}</td>
</tr>
<!-- Start Forum Row //-->
<tr>
	<td colspan="4" class="forum_row">{forum_name}</td>
</tr>
<!-- End Forum Row //-->
<tr>
	<td colspan="4">&nbsp;</td>
</tr>
<!-- End Category //-->

The outermost blocks (category) shows up fine.. however inside of each category block, all of the forum rows from every category block are showing up. I need each category block to show the relevant forum row blocks.

I'm thinking I need more than a 2d multi-dimensional array to nest X levels deep, but I'm not sure; and can't quite get my head around it.

I hope I've explained my problem well. Any help?