Jump to content

PHP Template Class Rendering with Arrays/Loops/PregMatch/PregReplace


Solar
Go to solution Solved by requinix,

Recommended Posts

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);
    }
}

 

Edited by Solar
Link to comment
Share on other sites

  • Solution

This "2D" array is actually just a regular array like everything else, except that the keys are named like "0" and "1" instead of "logos".

If I understand the way this works correctly, you should be able to write something like (0)(/name)(/0) to get Steven. If you don't want to write (0) or (1) then you'll have to figure out some new syntax...

Link to comment
Share on other sites

why not add the arrays using the assignment operator (=)? array_push doesn't do what you want for reasons that i have forgotten. You could read the manual for a better explanation anyway. I do something similar in my nature/biology website:

$multi = array();
$steven = array("name" => "Steven", "age" => 34);
$jason = array("name" => "Jason", "age" => 32);

$multi[] = $steven;
print_r($multi);

echo '<br>';

$multi[] = $jason;
print_r($multi);
	

the only problem with this method is that the multi array has its own numbered keys, thus it is now a multidimensional array. So you would need to loop over the multi array with this in mind.

maybe this helps? wait for other better answers from more experienced programmers.

Edited by jodunno
formatting code
Link to comment
Share on other sites

just to clarify: i mean that you could build an array with name and age as keys and just loop over the data.

$multi2 = array();
$multi2['name'][] = $steven['name'];
$multi2['name'][] = $jason['name'];

$multi2['age'][] = $steven['age'];
$multi2['age'][] = $jason['age'];
print_r($multi2);

 

Link to comment
Share on other sites

13 hours ago, requinix said:

This "2D" array is actually just a regular array like everything else, except that the keys are named like "0" and "1" instead of "logos".

If I understand the way this works correctly, you should be able to write something like (0)(/name)(/0) to get Steven. If you don't want to write (0) or (1) then you'll have to figure out some new syntax...

Yes thanks, I guess that could work and my loop function could work as follows:

        protected function loop($output, $key, $values){
            $pattern = "/\($key\)(.*?)\(\/$key\)/s";
            preg_match($pattern, $output, $matches);
            $section = $matches[1] ?? '';
            $result = '';
            $out = $section;
            foreach($values as $key => $value){
                $out = str_replace("(/".$key.")", $value, $out);
            }
            $result .= $out;
            return preg_replace($pattern, $result, $output);
        }

HTML:

<div>
	(0)<b>(/name)</b> (/age)(/0)
	(1)<b>(/name)</b> (/age)(/1)
</div>

This would be great for fixed results. I could write another loop function to check the output and if there is any (/name)s or (/age)s that are not filled in, strip/replace/fill them with blanks. This would be great for pagination rows/lists/tables or even a fixed navigation!

@jodunno I appreciate your help but I just used push as an example. There is nothing wrong with using push if you need to add multiple arrays inside a one-liner -- while array[] does save time if adding one or two. My question which was geared more towards the Template class in how I can loop. 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.