Convert a String to Variable

后端 未结 9 2108
臣服心动
臣服心动 2020-12-01 05:43

I\'ve got a multidimensional associative array which includes an elements like

$data[\"status\"]
$data[\"response\"][\"url\"]
$data[\"entry\"][\"0\"][\"text\         


        
相关标签:
9条回答
  • 2020-12-01 06:29

    Perhaps this option is also suitable:

    $data["entry"]["0"]["text"];
    $string = 'data["entry"]["0"]["text"]';
    
    function getIn($arr, $params)
    {
        if(!is_array($arr)) {
            return null;
        }
        if (array_key_exists($params[0], $arr) && count($params) > 1) {
            $bf = $params[0];
            array_shift($params);
            return getIn($arr[$bf], $params);
        } elseif (array_key_exists($params[0], $arr) && count($params) == 1) {
    
            return $arr[$params[0]];
        } else {
            return null;
    }
    }
    
    preg_match_all('/(?:(\w{1,}|\d))/', $string, $arr_matches, PREG_PATTERN_ORDER);
    
    array_shift($arr_matches[0]);
    print_r(getIn($data, $arr_matches[0]));
    

    P.s. it's work for me.

    0 讨论(0)
  • 2020-12-01 06:32

    PHP's variable variables will help you out here. You can use them by prefixing the variable with another dollar sign:

    $foo = "Hello, world!";
    $bar = "foo";
    echo $$bar; // outputs "Hello, world!"
    
    0 讨论(0)
  • 2020-12-01 06:32

    I was struggling with that as well, I had this :

    $user  =  array('a'=>'alber', 'b'=>'brad'...);
    
    $array_name = 'user';
    

    and I was wondering how to get into albert.

    at first I tried

    $value_for_a = $$array_name['a']; // this dosen't work 
    

    then

    eval('return $'.$array_name['a'].';'); // this dosen't work, maybe the hoster block eval which is very common
    

    then finally I tried the stupid thing:

    $array_temp=$$array_name;
    $value_for_a = $array_temp['a'];
    

    and this just worked Perfect! wisdom, do it simple do it stupid.

    I hope this answers your question

    0 讨论(0)
提交回复
热议问题