php - Convert a string into an associative array key?

Solution:

You can explode the string into an array and loop through the array. (DEMO)

/**
 * This is a test array
 */
$testArray['property']['entry']['item'] = 'Hello World';

/**
 * This is the path
 */
$string = 'property.entry.item';

/**
 * This is the function
 */
$array = explode('.', $string);

foreach($array as $i){
    if(!isset($tmp)){
        $tmp = &$testArray[$i];
    } else {
        $tmp = $tmp[$i];
    }
}

var_dump( $tmp ); // output = Hello World

Answer

Solution:

Split the string into parts, and itterate the array, accessing each element in turn:

function arrayDotNotation($array, $dotString){
    foreach(explode('.', $dotString) as $section){
        $array = $array[$section];
    }
    return $array;
}

$array = ['one'=>['two'=>['three'=>'hello']]];
$string = 'one.two.three';
echo arrayDotNotation($array, $string); //outputs hello

Live example: http://codepad.viper-7.com/Vu8Hhy

Answer

Solution:

You should really check to see if keys exist before you reference them. Otherwise, you're going to spew a lot of warnings.

function getProp($array, $propname) {   
    foreach(explode('.', $propname) as $node) {
        if(isset($array[$node]))
            $array = &$array[$node];
        else
            return null;
    }
    return $array;
}

Now you can do things like:

$x = array(
    'name' => array(
        'first' => 'Joe',
        'last' => 'Bloe',
    ),
    'age' => 27,
    'employer' => array(
        'current' => array(
            'name' => 'Some Company',
        )
    )
);

assert(getProp($x, 'age') == 27);
assert(getProp($x, 'name.first') == 'Joe');
assert(getProp($x, 'employer.current.name') == 'Some Company');
assert(getProp($x, 'badthing') === NULL);
assert(getProp($x, 'address.zip') === NULL);

Or, if you are only interested in the import section of the tree:

getProp($x['import'], 'some.path');

Source