Recently I encountered a small problem with a library downloaded from github or sourceforge (I don’t remember exactly), but quite old, with many functions used on the old style, many of them already deprecated.
Another problem encountered was the evaluation of a string and its transformation into an array, the internal representation being of a multi-vector array.
The original solution used the eval
function, a programming mode with which I do not agree, plus the code was no longer up to date, it generates many errors, so I found another solution and at least for my needs, the results are exactly what I wanted.
Suppose we have the following string:
$strdef = 'regrinfo.domain.name';
and we want to transform it into an array variable (matrix type) of the following form:
$strarr["regrinfo"]["domain"]["name"]=0;
which we use in a certain context.
The solution I used involves transforming the string into a json
format and then converting it to array:
function getvarname_arr($strdef, $init='0') { $init = json_encode($init); $parts = explode('.',rtrim($strdef,'.')); $varjson = '{"'.implode('":{"', $parts).'":'.$init.str_repeat('}',count($parts)); $result = json_decode($varjson,true); return $result; }
the result of the function will be something like:
Array ( [regrinfo] => Array ( [domain] => Array ( [name] => 0 ) ) )
Now, if we want the results of the function to be concatenated into a single array, then we need to use the function as in the following example:
$full_array = [];
...
#foreach ...
...
$strdef = function_to_init_strings($params1);
if ($strdef != '') {
$initvalue = function_to_init_value($params2);
if ($initvalue='') {
$temp_arr = getvarname_arr($strdef, $initvalue);
$full_array = array_merge_recursive($full_array, $temp_arr);
}
}
...
#endforeach
...
and is exactly what I need!
Happy coding!
Leave a Reply
Your email address will not be published. Required fields are marked *