dqhbuwrwq692118284 2016-08-23 02:01
浏览 233
已采纳

php:如何使用变量变量通过索引获取数组中的元素

If I have:

<?php
$params=[
    [
        'string'
    ]
];
//params get from $this->params()->fromPost();
$abc='params[0][0]';//$abc dynamiccly

I cannot access $params[0]

How to get string element?

I try to use

echo $$abc;

But

Notice: Undefined variable params[0][]

  • 写回答

3条回答 默认 最新

  • dortmundbvb0624 2016-08-23 02:12
    关注

    If $abc is defined dynamically, you have to split it in two variables : $arrayName and $arrayKey, as such :

    $params = array('string');
    $abc = 'params[0]';
    $arrayName = substr($abc,0,strpos($abc,'['));
    $arrayIndex = preg_replace('/[^\d\s]/', '',$abc);
    echo ${$arrayName}[$arrayIndex]; // returns "string"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?