Über die Methode „getValue“ lassen sich die Werte eines mehrdimensionalen Arrays mit der folgenden Notation auslesen: „Key/Key/Key/..“. Ein möglicher Anwendungsfall wäre das Einlesen einer Konfiguration, die in Form eines Arrays vorliegt.
Code:
function getValue($sPath, $aArray)
{
foreach(explode('/', $sPath) as $sKey)
$aArray=&$aArray[$sKey];
return $aArray;
}
{
foreach(explode('/', $sPath) as $sKey)
$aArray=&$aArray[$sKey];
return $aArray;
}
Beispiel:
function getValue($sPath, $aArray)
{
foreach(explode('/', $sPath) as $sKey)
$aArray=&$aArray[$sKey];
return $aArray;
}
$aConfiguration = array();
$aConfiguration['server']['host'] = "localhorst";
$aConfiguration['server']['user'] = "admin";
$aConfiguration['server']['password'] = "supersicher";
$aConfiguration['directories']['home']['user1'] = array('Files', 'Docs', 'Pictures');
$aConfiguration['directories']['home']['user2'] = array('Backup', 'Code', 'Projects');
$aConfiguration['directories']['home']['user3'] = array('Music', 'Games', 'Pictures');
$aPaths = array('directories/home/user1',
'directories/home/user2',
'directories/home/user3',
'server/host',
'server/user',
'server/password'
);
foreach($aPaths as $sPath)
{
print_r(getValue($sPath, $aConfiguration));
echo "<br/>";
}
/*
Ausgabe:
Array ( [0] => Files [1] => Docs [2] => Pictures )
Array ( [0] => Backup [1] => Code [2] => Projects )
Array ( [0] => Music [1] => Games [2] => Pictures )
localhorst
admin
supersicher
*/
{
foreach(explode('/', $sPath) as $sKey)
$aArray=&$aArray[$sKey];
return $aArray;
}
$aConfiguration = array();
$aConfiguration['server']['host'] = "localhorst";
$aConfiguration['server']['user'] = "admin";
$aConfiguration['server']['password'] = "supersicher";
$aConfiguration['directories']['home']['user1'] = array('Files', 'Docs', 'Pictures');
$aConfiguration['directories']['home']['user2'] = array('Backup', 'Code', 'Projects');
$aConfiguration['directories']['home']['user3'] = array('Music', 'Games', 'Pictures');
$aPaths = array('directories/home/user1',
'directories/home/user2',
'directories/home/user3',
'server/host',
'server/user',
'server/password'
);
foreach($aPaths as $sPath)
{
print_r(getValue($sPath, $aConfiguration));
echo "<br/>";
}
/*
Ausgabe:
Array ( [0] => Files [1] => Docs [2] => Pictures )
Array ( [0] => Backup [1] => Code [2] => Projects )
Array ( [0] => Music [1] => Games [2] => Pictures )
localhorst
admin
supersicher
*/