0

I have classes, each with a date related member variable that always has the same naming format - field_{$node->type}_date

For example, if I my node type was 'car', the date field would be named field_car_date

So I am looping over all my nodes and I want to access the date related field for each of them. However I am getting an error. Here's the code

$date_field_key = 'field_' . $node->type . '_date';
if (isset($node->$date_field_key['und'][0]['value'])) {

I get an error because of the second line. The error is - Illegal string offset 'und' The date related variable is an array and it does have an element with the key 'und'. If I write out the line explicitly - $node->field_car_date['und'][0]['value'] - it works fine. It's just when I dynamically create the field name that I get this problem.

Any solution for this, is my syntax incorrect?

1
  • The syntax is not incorrect, but you express something else with it as you obviously intend to. Commented Aug 12, 2012 at 20:05

2 Answers 2

5

You need to surround you key value in {} because it's a dynamically-assigned variable.

In your second line, you have $node->$date_field_key['und'][0]['value'] where you should have:

$node->{$date_field_key}['und'][0]['value']

Notice the {} surrounding the date_field_key

Good luck!

Sign up to request clarification or add additional context in comments.

3 Comments

Try: $node->{$date_field_key}['und'][0]['value'] instead.
I'm pretty sure that is not called objet declaration. A little bit more precision with an answer won't be bad, because it is an answer and others expect a certain level of guidance with it.
You seem to be following me around today, hakra :)
2

There is no reason to spare the variable:

$array = $this->$date_field_key;
$value = $array['und'][0]['value'];

If you get it to work, we then can discuss more advanced topics.

Comments

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.