php 将字符串转换为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/433302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:44:08  来源:igfitidea点击:

Convert a String to Variable

phparraysstringvariables

提问by Gilean

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

我有一个多维关联数组,其中包含一个元素,如

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

I've got a strings like:

我有一个像这样的字符串:

$string = 'data["status"]';
$string = 'data["response"]["url"]';
$string = 'data["entry"]["0"]["text"]';

How can I convert the strings into a variable to access the proper array element? This method will need to work across any array at any of the dimensions.

如何将字符串转换为变量以访问正确的数组元素?此方法需要在任何维度的任何数组上工作。

回答by clawr

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

PHP 的可变变量将在这里帮助您。您可以通过在变量前加上另一个美元符号来使用它们:

$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"

回答by Allain Lalonde

Quick and dirty:

又快又脏:

echo eval('return $'. $string . ';');

Of course the input string would need to be be sanitized first.

当然,输入字符串需要先进行清理。

If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.

如果你不喜欢快速和肮脏......那么这也可以工作,它不需要 eval 这甚至让我感到畏缩。

It does, however, make assumptions about the string format:

但是,它确实对字符串格式做出了假设:

<?php
$data['response'] = array(
    'url' => 'http://www.testing.com'
);

function extract_data($string) {
    global $data;

    $found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
    if (!$found_matches) {
            return null;
    }

    $current_data = $data;
    foreach ($matches[1] as $name) {
            if (key_exists($name, $current_data)) {
                    $current_data = $current_data[$name];
            } else {
                    return null;
            }
    }

    return $current_data;
} 

echo extract_data('data["response"]["url"]');
?>

回答by Brandon S

This can be done in a much simpler way. All you have to do is think about what function PHP provides that creates variables.

这可以通过更简单的方式完成。您所要做的就是考虑 PHP 提供的创建变量的函数。

$string = 'myvariable';
extract(array($string => $string));
echo $myvariable;

done!

完毕!

回答by gus

You can pass by reference with the operator &. So in your example you'll have something like this

您可以使用运算符通过引用传递&。所以在你的例子中你会有这样的东西

$string = &$data["status"];
$string = &$data["response"]["url"];
$string = &$data["entry"]["0"]["text"];

Otherwise you need to do something like this:

否则你需要做这样的事情:

$titular = array();
for ($r = 1; $r < $rooms + 1; $r ++)
{
    $title = "titular_title_$r";
    $firstName = "titular_firstName_$r";
    $lastName = "titular_lastName_$r";
    $phone = "titular_phone_$r";
    $email = "titular_email_$r";
    $bedType = "bedType_$r";
    $smoker = "smoker_$r";

    $titular[] = array(
        "title" => $$title,
        "first_name" => $$firstName,
        "last_name" => $$lastName,
        "phone" => $$phone,
        "email" => $$email,
        "bedType" => $$bedType,
        "smoker" => $$smoker
    );
}

回答by Dima Storozhuk

There are native PHP function for this: use http://php.net/manual/ru/function.parse-str.php(parse_str()).

有本机 PHP 函数:使用http://php.net/manual/ru/function.parse-str.php(parse_str())。

don't forget to clean up the string from '"' before parsing.

不要忘记在解析之前清理 '"' 中的字符串。

回答by kalitin.nikita

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.

Ps这对我有用。

回答by MattBelanger

You would access them like:

您可以像这样访问它们:

print $$string;

回答by Gilean

Found this on the Variable variablespage:

变量变量页面上找到了这个:

function VariableArray($data, $string) { 
    preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER); 

    $return = $arr; 
    foreach($arr_matches[1] as $dimension) { $return = $return[$dimension]; }

    return $return; 
} 

回答by user763694

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

我希望这回答了你的问题