将字符串转换为变量 [英] Convert a String to Variable

查看:27
本文介绍了将字符串转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维关联数组,其中包含像

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

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

我有一个字符串:

$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.

推荐答案

又快又脏:

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

当然,输入字符串需要先清理.

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

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

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

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

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

这篇关于将字符串转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆