views:

3885

answers:

4

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.

A: 

You would access them like:

print $$string;

mabwi
-1 This doesn't work.
Triptych
You're right, it doesn't work with the arrays. Should've tested better.
mabwi
+6  A: 

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.

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"]');
?>
Allain Lalonde
A: 

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

$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"
TenebrousX
I wasn't aware that this worked with nested arrays.
Allain Lalonde
This solved a problem for me; wasn't aware of variable variables. Thanks!
Greg Harman
A: 

Found this on the Variable variables page:

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; 
}
Gilean
Pretty sure this wouldn't work with double quotes around field names, and if the $string was invalid... I'm pretty sure it'd crash.
Allain Lalonde
Correct, my quick test showed that you need to use something like: [entry][0][text]
Gilean