简体   繁体   中英

Convert a string into an associative array key?

Given a string that contains values separated by dots:

property.entry.item

What is the best way to convert that to a key for an associative array?

$result['imported_data']['property']['entry']['item']

The string may be of any length, with any number of dots and contain an value:

people.arizona.phoenix.smith

I've tried the following without success:

//found a dot, means we are expecting output from a previous function
if( preg_match('[.]',$value)) {

    //check for previous function output
    if(!is_null($result['import'])) {

        $chained_result_array = explode('.',$value);

        //make sure we have an array to work with
        if(is_array($chained_result_array)) {

            $array_key = '';
            foreach($chained_result_array as $key) {

                $array_key .= '[\''.$key.'\']';
            }

        }
        die(print_r(${result.'[\'import\']'.$array_key}));
    }
}

I was thinking I could convert the string to a variable variable, but I get an array to string conversion error.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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