使用以特殊字符开头的键获取关联数组

时间:2018-05-31 11:12:56

标签: php arrays object

我有如下的数组

Array
(
    [0] => stdClass Object
        (
            [id] => 67
            [contact_id] => 
            [status] => Complete
            [is_test_data] => 0
            [datesubmitted] => 2018-05-24 03:56:35
            [SessionID] => 1527148487_5b066fc7bdcd75.00827785
            [Language] => English
            [datestarted] => 2018-05-24 03:54:47
            [iLinkID] => 6528804
            [sResponseComment] => 
            [responseID] => 67
            [[question(9)]] => Yes
            [[question(24)]] => Satisfied
            [[question(25)]] => 
            [[question(26)]] => 
            [[question(27)]] => 
            [[question(28)]] => 
            [[question(29)]] => 
            [[question(31)]] => Likely
            [[question(32)]] => 
            [[question(33)]] => 26-35
            [[question(35)]] => Male
            [[question(36)]] => 
            [[question(37)]] => No
)
)

我试图推导出如下

Array
(
    [0] => Array
        (
            [id] => 67
            [submitted] => 2018-05-24 03:56:35,
            [question_9]=>yes

        )
)

我只是尝试了array_map

$derived=array_map(function ($a){ return array('id'=>$a->id,
                                                'submitted'=>$a->datesubmitted,
                                                 'question_9'=>$a->[question(9)]//this is not a right way, what is best practice
                                                );

                               }, $survey_array);

error :Parse error: syntax error, unexpected '[', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in

1 个答案:

答案 0 :(得分:3)

在访问对象属性时,您可以使用花括号来包装特殊字符:

$a->{'[question(9)]'}

注意:这不是一个关联数组。从您的初始输出,$ a是stdClass对象。