Bar*_*hje 4 php arrays variable-variables
我真的不知道如何描述这个问题,所以如果标题有点不清楚,我很抱歉.
我有一个带有数组字段的对象.我得到了存储在变量中的这些字段的名称,我希望在其中一个数组字段中找到一个元素.例如
$field_name = 'array_field';
$object = new stdClass();
$object->array_field= array('this', 'is', 'an', 'array);
Run Code Online (Sandbox Code Playgroud)
我知道我可以访问数组$object->$field_name,但是现在我想通过$field_name变量访问它来访问数组中的键.例如(显然不起作用)$object->$field_name[0]
Kel*_*Kel 14
我想,您应该使用以下内容:
$object->{$field_name}[0]
Run Code Online (Sandbox Code Playgroud)
它在PHP手册的"变量变量"部分详细描述:http://www.php.net/manual/en/language.variables.variable.php
顺便说一句,根据我的经验,这种字段操作方式可能导致代码模糊 - 如果可能的话,我建议使用关联数组.