Beispiel, ich habe folgende Datenstruktur:
Dazu habe ich einen Pfad in das Array:
Und hänge nun neue Daten an der via $path angegebenen Position ein:
Das funktioniert so und ergibt:
Zwar kommen alle Daten aus einer DB, nur kommt der Weg über eval() (habe ich irgendwo so abgekupfert) trotzdem ein wenig befremdlich vor. Hat jemand noch eine gute Idee wie ich sonst schreibend auf eine beliebige Stelle in einem (bestehenden) multidimensionalen Array zugreifen kann, ohne eval() und ohne die Verschachtelungstiefe oder die Keys fest einzuprogrammieren?
P.S. $path wird dynamisch aus einem gegebenen Key erzeugt:
PHP-Code:
$data = array(
1 => array('a', 'b', 'c'),
2 => array('d', 'e', 'f' => array('g', 'h', 'i')),
3 => array('j', 'k', 'l')
);
PHP-Code:
$path = array(2, 'f');
PHP-Code:
$virtualArray = '';
foreach($path as $curKey)
{
$virtualArray .= '[\'' . $curKey . '\']';
}
eval('$data' . $virtualArray . '[\'m\'] = array(\'x\', \'y\', \'z\');');
PHP-Code:
$data = array(
1 => array('a', 'b', 'c'),
2 => array('d', 'e', 'f' => array('g', 'h', 'i', 'm' => array('x', 'y', 'z'))),
3 => array('j', 'k', 'l')
);
P.S. $path wird dynamisch aus einem gegebenen Key erzeugt:
PHP-Code:
/**
* recursive search for key in a multidimensional array and return path as array
* based on http://www.sitepoint.com/forums/showthread.php?p=4553691#post4553691
* inserted "array_pop($stack); continue;" to switch back from deeper to lower levels, if key not yet found
*
* @license Do-whatever-you-want-to-do-with-this-code-License
* @param array heystack multidimensional array to search in
* @param string needle key to be found
* @param array stack current path
* @return array path to key or false if not found
*/
function arrayKeyPath($heystack, $needle, $stack = array())
{
if(is_array($heystack))
{
foreach($heystack as $k => $v)
{
if($k == $needle)
{
array_push($stack, $k);
return $stack;
}
if(is_array($v))
{
array_push($stack, $k);
$out = arrayKeyPath($v, $needle, $stack);
if($out == false)
{
array_pop($stack);
continue;
}
else
{
return $out;
}
}
}
return false;
}
else
{
return false;
}
}
Kommentar