0

I am trying to fetch an object:

$field_name= 'field_test';
$json_code = $node->$field_name['und'][0]['value'];

NOT WORKING

$json_code = $node->field_test['und'][0]['value'];

WORKING

I must have variable because it's every time different field name

any solution?

2
  • $var = $node->$field_name; $json = $var['und'][0]['value'];
    – Clive
    Apr 24, 2014 at 9:45
  • Thx that worked!!
    – josaric
    Apr 24, 2014 at 10:42

2 Answers 2

5

Your PHP is incorrect for what you're trying to accomplish.

Drupal has field_get_items() for this purpose, though:

$items = field_get_items('node', $node, $field_name);
...
2

Clive is right about field_get_items() but if for some reason you absolutely want it the way you wrote it, then this will work ( notice the curly braces ) :

$json_code = $node->{$field_name}['und'][0]['value']

Though you should replace ['und'] with the constant LANGUAGE_NONE, e.g. :

$json_code = $node->{$field_name}[LANGUAGE_NONE][0]['value']

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.