note 80839 deleted from ref.array by levim

From: Date: Tue, 06 May 2014 22:00:59 +0000
Subject: note 80839 deleted from ref.array by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-199440@lists.php.net to get a copy of this message
Note Submitter: christian dot reinecke at web dot de ---- Here are two more functions handling string2array and access array by string. It's useful if you want to access an array in xpath-style, such as parse_ini_file return values with $process_sections = TRUE. <?php function createArrayByString($string, $separator, $value = NULL) { if (strlen($string) > 0) { $splitter = explode($separator, $string); $index = array_shift($splitter); // get first element $function = __FUNCTION__; return array($index => $function(implode($separator, $splitter), $separator, $value)); } return $value; } function accessArrayByString($array, $string, $separator, $default = NULL) { if (!is_array($array)) { return empty($string) ? $array : $default; } @list ($key, $rest) = explode($separator, $string, 2); // @ needed for last access $function = __FUNCTION__; return array_key_exists($key, $array) ? $function($array[$key], $rest, $separator, $default) : $default; } $string = "one.two.three.four"; $separator = "."; $array = createArrayByString($string, $separator, "standard value"); $return = accessArrayByString($array, $string, $separator, "element not found"); var_dump($array); // should return array("one" => array("two" => array("three" => array("four" => "standard value")))) var_dump($return); // should return "standard value"; ?> change the function name to what ever you want, the recursive call uses __FUNCTION__ for re-call.

« previous php.notes (#199440) next »