I am using multidimensional arrays and am accessing them after using explode on a string. The resulting array should be nested with the number of occurrences of '.' in the given string. For instance, foo.bar.ok is ['foo']['bar']['ok'].
Currently, I am doing:
switch (count($_match)):
case 1:
$retVal = str_replace('{' . $match . '}', $$varName[$_match[0]], $retVal);
break;
case 2:
$retVal = str_replace('{' . $match . '}', $$varName[$_match[0]][$_match[1]], $retVal);
break;
case 3:
$retVal = str_replace('{' . $match . '}', $$varName[$_match[0]][$_match[1]][$_match[2]], $retVal);
break;
endswitch;
Quintessentially I would like to have unlimited number of $_match[x] using a loop.
Edit The resulting array should be in the format: $array[foo][bar][ok]
Here are some examples I tried:
$string = 'foo.bar.ok';
$exploded = explode('.', $string);
$bracketed = array_map(function($x) { return [$x]; }, $exploded);
echo "<pre>";var_dump($bracketed);
$bracketed = array_map(function($x) { return "['$x']"; }, $_match);
$result = implode('', $bracketed);
var_dump(eval('return $t' . $result . ';'));
The first doesn't append arrays in nested structure, it lists them as 0, 1, 2, etc and the second works but it uses eval.
Finally, using loops as suggested worked.
for ($replace = $$varName[$_match[0]], $i = 1; $i < count($_match); $i++) {
if (isset($replace[$_match[$i]]))
$replace = $replace[$_match[$i]];
}
if (is_string($replace) || is_numeric($replace))
$retVal = str_replace('{' . $match . '}', $replace, $retVal);
I would like to see a working array_walk example though? - thank you!
$_matcharray will contain. Also, it's hard to determine what you're trying to do because yourfor()code does not do the same thing as your initialswitch()code. Theswitch()code does a singlestr_replace()while thefor()loop does multiplestr_replace(), and also has checks foris_string()andis_numeric(). In any case, why don't you try thearray_walk()method yourself and post the results if you have problems?