I have a Template class that accepts single values and 3d multidimensional arrays.
So, if I provide a simple array: array("name"=>"Steven", "age" => 34); it works nicely by looping and replacing the HTML (/name) and (/age).
foreach($this->values as $key => $value){
$output = str_replace("(/".$key.")", $value, $output);
}
If I provide it with a multidimensional array, it works too.
Example: array("logos" => $portfolio->getPortfolioByCat("2"));
//puts an array inside of an array so that the HTML file can loop between (logos)(/name)(/image)..etc(/logos)
I'm struggling with a 2d (I think?) array.
Here's an example: Let's say I have two names and ages and push into one array.
$multi = array();
$steven = array("name" => "Steven", "age" => 34);
$jason = array("name" => "Jason", "age" => 32);
array_push($multi,$steven,$jason);
I now have two (/name) and two (/age).
I do not wish to load the view template twice (or multiple times). I would like to reference once and echo the output multiple times but I'm stumped.
The template class below is an example of how the 3d array loops which is called by a render function. Since my 2d array above does not contain an actual unique key and a values that is an array, how can safely loop through? Or do you recommend that I wrap it into another array (seems repetitive) that contains a key. $newMulti = array("names" => $newMulti) and the html would be (names)(/name)(/age)(/names).
class Template{
//variables
//render function (grabs template file, sets an output, calls the loop function, echo the results in output)
protected function loop($output, $key, $values){
$pattern = "/\(\$key\)(.*?)\(\/$key\)/s";
preg_match($pattern, $output, $matches);
$section = $matches[1] ?? '';
$result = '';
foreach($values as $item){
$out = $section;
foreach($item as $key => $value){
$out = str_replace("(/".$key.")", $value, $out);
}
$result .= $out;
}
return preg_replace($pattern, $result, $output);
}
}