0

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?

2 Answers 2

1

If your array is single dimensional than you can simply type hint that array as an object like as

$values = array(
     "data1" => "example1",
     "data2" => "example2",
);

$values = (object) $values;

echo $values->data1;//example1
Sign up to request clarification or add additional context in comments.

Comments

0

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"
}

1 Comment

Solved! Many Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.