Q:

Create new attributes inside a PHP object, through external values

In my case I'm creating a module for Drupal passing datasets from a database to another. I want to use the default function node_save(), so I need to create a node object with a stdClass().
Once I've exported the dataset into an array like in this example:
 $values = array(
     "data1" => "example1",
     "data2" => "example2",
     ...
 );

I need to put the values in this way
$node = stdClass();
$node->title = 'Example';

Running through the array it could be easier create an attribute like title and pass it the interested value like:
foreach ($values as $key) {
   $node->$key = $values[$key];
}

There's a way to create the attribute automatically like
$node->$key

And pass it a value?

A:

Try this one (instead of $node->$key try to use $node->{$key}):
foreach ($values as $key => $val) {
   $node->{$key} = $val;
}

For your example array:
$values = array(
     "data1" => "example1",
     "data2" => "example2",
     ...
 );

The code above will output:
$node->data1 = "example1";
$node->data2 = "example2";

object(stdClass)#1 (2) {
  ["data1"]=> string(8) "example1"
  ["data2"]=> string(8) "example2"
}

