Able to see a variable in print_r()'s output, but not sure how to access it in code

后端 未结 9 682

I googled, installed Devel, Drupal for Firebug, but I can\'t find it.

I found what I want, I know where it is; I just don\'t know how to g

9条回答
  •  既然无缘
    2020-11-22 03:04

    Whenever you need to read a value out of a variable, you need to know which expression you need to formulate to access that value.

    For a simple variable value this is simple, you just take the variable name and access it as a variable by prefixing it with the $ sign:

    var_dump($variable);
    

    This is documented here.

    However this does only work for simple datatypes like string or integer. There are as well compound datatypes, namely array and object. They can contain further datatypes, be it simple or compound. You can learn in the PHP manual how to access the values of an array and how you can access them from an object. I think you already know of that a bit, so just for having it linked here.

    When you have learned about that, you can then combine this. E.g. if there is an array within an object and therein is a string you would like to get, you need to combine the $ sign and the variable name with the needed accessors, property names and array keys. Then you get your value. The data you have posted shows that you have an object that has some other objects and arrays and in the end you find the variable name.

    Some combination example:

    var_dump($variable->handler->view[0]->_field_data);
    

    This is based on the data you've provided above. $variable is where you start, -> is used to access object members which need to be named then (like a name for a variable) : handler. As you've seen in your debug output that handler is an object, you need to use again the -> to access the view member of it.

    Now view is different because it's an array. You access values of an array by using [] and putting the key in there. The key in my example is a number, 0. And as the value of that array entry is an object again, in the next step you need to use -> again.

    You can continue this game until you reach the element that you're interested in. The debug output you already have helps you to write the expression that returns the value. Possibly it is:

    $field_image->handler->view->result[0]->_field_data['nid']['entity']->field_image['und'][0]['filename']
    

    But I can not validate that here on my system in full.

    However when finding things out, it's helpful to make use of var_dump as you could step by step extend the expression until you find the element. If you make an error you will immediately see. Sometimes it helps to place a die(); after the var_dump statement so not to end the response before it contains to much other data that will hide the information from you. The devel plugin offers additional debug routines to dump values prominent.

提交回复
热议问题