简体   繁体   English

将字符串转换为变量

[英]Convert a String to Variable

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.此方法需要在任何维度的任何数组上工作。

PHP's variable variables will help you out here. PHP的变量变量将帮助你。 You can use them by prefixing the variable with another dollar sign: 您可以通过在变量前添加另一个美元符号来使用它们:

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

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"]');
?>

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! 完成了!

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
    );
}

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. 不要忘记在解析之前从'''清除字符串。

您可以访问它们,如:

print $$string;

Found this on the Variable variables page: Variable variables页面上找到了这个:

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; 
} 

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]));

Ps it's work for me. 这对我有用。

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 我希望这回答了你的问题

You can also use curly braces (complex variable notation) to do some tricks:您还可以使用花括号(复杂的变量符号)来做一些技巧:

$h = 'Happy';
$n = 'New';
$y = 'Year';
$wish = ${$h.$n.$y};
echo $wish;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM