Php reading object variable as part of other varia

2019-08-23 01:08发布

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条回答
老娘就宠你
2楼-- · 2019-08-23 01:26

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;
}
查看更多
登录 后发表回答