php call array from string

后端 未结 4 398
面向向阳花
面向向阳花 2021-01-23 02:57

I have a string that contains elements from array.

$str = \'[some][string]\';
$array = array();

How can I get the value of $array[\'some\

相关标签:
4条回答
  • 2021-01-23 03:36
    // trim the start and end brackets    
    $str = trim($str, '[]');
    // explode the keys into an array
    $keys = explode('][', $str);
    // reference the array using the stored keys
    $value = $array[$keys[0][$keys[1]];
    
    0 讨论(0)
  • 2021-01-23 03:48

    You can do so by using eval, don't know if your comfortable with it:

    $array['some']['string'] = 'test';    
    $str = '[some][string]';    
    $code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));    
    $value = eval($code);    
    echo $value; # test
    

    However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.

    Another example if you need to write access to the array item, you can do the following:

    $array['some']['string'] = 'test';
    $str = '[some][string]';
    $path = explode('][', substr($str, 1, -1));
    $value = &$array;
    foreach($path as $segment)
    {
        $value = &$value[$segment];
    }
    
    echo $value;
    $value = 'changed';
    print_r($array);
    

    This is actually the same principle as in Eric's answer but referencing the variable.

    0 讨论(0)
  • 2021-01-23 03:48

    This will work for any number of keys:

    $keys = explode('][', substr($str, 1, -1));
    $value = $array;
    foreach($keys as $key)
        $value = $value[$key];
    
    echo $value
    
    0 讨论(0)
  • 2021-01-23 03:52

    I think regexp should do the trick better:

    $array['some']['string'] = 'test';
    $str = '[some][string]';
    if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
    {
        if (isset($array[$keys['key1']][$keys['key2']]))
             echo $array[$keys['key1']][$keys['key2']]; // do what you need
    }
    

    But I would think twice before dealing with arrays your way :D

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