I'm using a simple PHP template script which has a function sets the values to the key and later replace the template tags with the key.
<?php
class Template {
protected $file;
protected $values = array();
public function __construct($file) {
$this->file = $file;
}
public function set($key, $value) {
$this->values[$key] = $value;
}
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[@$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
?>
Then I have this foreach loop, I wanted to set all of the $post_title data to post_title, then output all the values, but I only got one element of data within the foreach loop.
<?php foreach ($post_titles as $post_title): ?>
<?php $data->set("post_title", $post_title['post_title']); ?>
<?php endforeach; ?>
<?php echo $data->output(); ?>
If I edit above code in the foreach loop to <?php echo $post_title['post_title']; ?> I will get all of the elements from the variable $post_titles which is an array, however, other ways like using return or set values to post_title will only get me one element from the array.
How can I get all of the data elements within the foreach loop, not by immediately echoing out, but saved into a variable for later use outside of the foreach loop.
post_titleon each iteration.$this->values[$key] = $valuewill there for be the same as$this->values['post_title'] = $valueon each iteration. That overwrites thepost_titleevery time it's called and you will only end up with the last post title.