user1319580
user1319580

Reputation: 165

Accessing multidimensional array in Drupal

This is as equally a drupal question as a PHP question, I assume.

I have the following print_r($node) array

stdClass Object
(
    [vid] => 4
...
    [field_imgleft] => Array
            (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => defaultimgleft
                            [format] => 
                            [safe_value] => defaultimgleft
                        )
                )
        )
)

field_imgleft is a field in the content type of the node. Since there will only be one value, [0] is the max for that array. I'm trying to return the value of [value] to a variable, but I am having no such luck with node-> methods or node[...] and so on.

Upvotes: 1

Views: 1577

Answers (2)

Morgan Delaney
Morgan Delaney

Reputation: 2439

I would suggest using the Devel module so you can tap into the dpm() function as an improved print_r();

dpm( $node->field_imgleft['und'][0]['value'] );

Upvotes: 2

Clive
Clive

Reputation: 36955

There's a built in API function to extract field values from an entity: field_get_items().

You can use it like so:

$items = field_get_items('node', $node, 'field_imgleft');

$first_item = array_shift($items);

$value = $first_item['value'];

This method is recommended over accessing the array directly as it takes care of the field translation for you...no need to worry about using 'und' any more.

Upvotes: 5

Related Questions