简体   繁体   English

使用变量时:致命错误:不能将字符串偏移量用作数组

[英]when using variable: Fatal error: Cannot use string offset as an array

The following piece of code: 以下代码:

$field = 'field_total_comments_added';
$current_user_count = $user_data->$field['und']['0']['value'];

returns an error: Fatal error: Cannot use string offset as an array 返回错误:致命错误:不能将字符串偏移用作数组

if I just use: 如果我只是使用:

$current_user_count = $user_data->field_total_comments_added['und']['0']['value'];

the code works just fine. 代码工作得很好。 In order to use some custom functionality I have to use the variable displayed in the first code block. 为了使用一些自定义功能,我必须使用第一个代码块中显示的变量。 How can I solve this? 我怎么解决这个问题?

Please tell me if the problem isn't clear to you. 如果问题不明确,请告诉我。

Thanks in advance for your assistance 提前感谢你的帮助

You can use this common workaround: 您可以使用以下常见解决方法:

$current_user_count = $user_data->{$field}['und']['0']['value'];

Which basically forces the variable property name to have precedence over the array access operator. 这基本上强制变量属性名称优先于数组访问运算符。

Try: 尝试:

$field = 'field_total_comments_added';
$current_user_count = ($user_data->$field)['und']['0']['value'];

It might only work for PHP 5.4. 它可能只适用于PHP 5.4。 For earlier versions, also try: 对于早期版本,还可以尝试:

$field = 'field_total_comments_added';
$item = $user_data->$field;
$current_user_count = $item['und']['0']['value'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM