Php reading object variable as part of other variable

筅森魡賤 提交于 2019-12-12 01:41:45

问题


I have an array structure of 60 elements. I'd like to use a for/foreach/while to read this structure.

This is what I have :

$this->details->field_link_01[0]['title']
$this->details->field_link_02[0]['title']
..
$this->details->field_link_60[0]['title']

And what i need is the following.

$myvar = eval ( "$this->details->field_link_" . $cont . "[0]['title']" )

What I have seen is PHP let to use $ as evaluation function

$myvar = ${"this->details->field_link_" . $cont . "[0]['title']" }

But it didn't work.

Is there any other solution ? Which PHP version ? 5.2 , 5.6 , 7 ?


回答1:


Have a look at Variable variables and sprintf.

for ($i = 1; $i <= 60; $i++) {
    $fieldName = sprintf("field_link_%02d", $i);
    $fieldLink = $this->details->$fieldName;

    $myvar = $fieldLink[0]['title'];

    echo $myvar;
}


来源:https://stackoverflow.com/questions/42649752/php-reading-object-variable-as-part-of-other-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!