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

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

问题描述

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

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.

推荐答案

快速和肮脏的:

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天全站免登陆