In an attempt to solve the problem I wrote the following function. In my Cake PHP install for Passbook I placed it in APP/config/bootstrap.php so that it is available everywhere.
// Dot notation array access
function dot(&$arr, $path = null, $checkEmpty = true, $emptyResponse = false) {
// Check path
if (!$path) user_error("Missing array path for array", E_USER_WARNING);
// Vars
$pathElements = split("\.", $path);
$path =& $arr;
// Go through path elements
foreach ($pathElements as $e) {
// Check set
if (!isset($path[$e])) return $emptyResponse;
// Check empty
if ($checkEmpty and empty($path[$e])) return $emptyResponse;
// Update path
$path =& $path[$e];
}
// Everything checked out, return value
return $path;
}To use this function using the previous example one would simply call dot($myArr, 'key1.key2') The parameter checkEmpty allows you to specify whether you want to check if the variable is empty or not, if not the value will be returned as long as it is set. The parameter emptyResponse lets you specify what to return if the is not found or found to be empty.
0 comments:
Post a Comment