开发者

Dynamically access an object property array element in PHP

I have an object, that I would like to interact with dynamically. I would like to rename the game1_team1 in:

$default_value = $individual_match->field_match_game1_team1[0]['value'];

to be game1_team2, game2_team1, game2_team2, game3_team1, etc. Based on the loop they开发者_Go百科 are in.

I have tried:

$dynamic = 'field_match_game'.$i.'_team'.$j;
$default_value = $individual_match->$dynamic[0]['value'];

but it returns

Fatal error: Cannot use string offset as an array

Update: Based on Saul's answer, I modified the code to:

$default_value = $individual_match->{'field_match_game'.$i.'_team'.$j}[0]['value'];

which got rid of the Fatal error, but doesn't return a value.


$individual_match->field_match_game1team1[0]['value'] = 'hello1';

$i = 1;
$j = 1;

$default_value = $individual_match->{'field_match_game'.$i.'team'.$j}[0]['value'];


'Renaming' is not possible unless you create a new property, and delete the old one. Access dynamic names like this:

$dynamic = "field_match_$i_team$j";
$default_value = $individual_match->$dynamic[0]['value'];

Note the $ between -> and dynamic.

Delete and create example:

$oldProperty = "field_match_1_team1";
$newProperty = "field_match_$i_team$j";
$hold = $individual_match->$oldProperty;
unset($individual_match->$oldProperty);
$individual_match->$newProperty = $hold;


Look at this : http://php.net/manual/en/function.get-class-vars.php You can list all object's properties in array and select only needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜