tags:

views:

25

answers:

3

I'm trying to populate a template with variables from a database. The data looks as follows:

id  field      content
1   title      New Website
1   heading    Welcome!
1   intro      This is a new website I have made, feel free to have a look around
2   title      About
2   heading    Read all about it!

What I need to do with that data is set properties of a $template object according to the field column and set said values to what's in the content column; e.g. for id = 1

$template->title = 'New Website';
$template->heading = 'Welcome!';
$template->intro = 'This is a new websi...';

I have the data in an array and I can easily loop over it but I just can't figure out how to get the properties to be the names of another variable. I've tried the variable variables approach but to no avail. Does that work with object properties?

Here's what I've got so far:

foreach($data as $field)
{
    $field_name = $field['field'];
    $template->$$field_name = $field['content'];
}

I've also tried using $template->${$field_name} and $template->$$field_name but so far no luck!

Can this be done?!

+2  A: 
$template->{$field_name}
Ignacio Vazquez-Abrams
Why didn't I try the simple ones first?! It's `$template->{$field_name}` but you definitely sent me down the right track!
Matt
@Matt: F​ixed​.
Ignacio Vazquez-Abrams
A: 

You're getting ahead of yourself.

try:

$template->$field_name;

Why does this work?

$foo = 'bar';
$object->bar = 1;

if ($object->$foo == $object->bar){
   echo "Wow!";
}
timdev
A: 

use

$template->{$field_name} = $field['content'];

or simply

$template->$field_name = $field['content'];
oezi