Home > other >  PHP multidimensional array: append indexed multidimensional array based on var
PHP multidimensional array: append indexed multidimensional array based on var

Time:07-12

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.

Thanks in advance

CodePudding user response:

Use array_map() and implode().

$string = 'foo.bar.ok';
$exploded = explode('.', $string);
$bracketed = array_map(function($x) { return "[$x]"; }, $exploded);
$result = implode('', $bracketed);

CodePudding user response:

So you want to perform $$varName[$_match[0]][$_match[1]][$_match[2]...[$_match[count($_match)-1]?

for ($var_name = $varName[$_match[0]], $i=1; $i<count($_match); $i  ) {
  $var_name = $var_name[$_match[$i]];
}
$retVal = str_replace('{' . $match . '}', $$var_name, $retVal);

This could probably be improved by replacing the for() with array_walk().

  •  Tags:  
  • php
  • Related