Hi everyone,
I'm a lazy programmer and when I want to create an array that I can store serialized in a database I don't feel like typing out all the array stuff rather I want to use a delimited string something like this:
access.read=1,2,3::
access.write=1,2::
access.modify=1,2::
access.manage=1::
somethingelse=10101
So I came up with this function that takes just that type of text information and converts it into a multi-dimensional array that I can later serialized and store into the database. The code looks like this:
function readConfigString($cnf){
// is the input valid
$out = array();
if(!is_null($cnf) && is_string($cnf)){
// clean up the input
$cnf = trim($cnf);
if(substr($cnf,-2) == '::'){
$cnf = substr($cnf,0,(strlen($cnf) - 2));
}
// breakdown the lines
$lines = split('::',$cnf);
foreach($lines as $line=>$data){
$valSets = split('=',$data);
if(strpos($valSets[0],".") > 1){
$names = split("\.",$valSets[0]);
$fname = trim(strtolower($names[0]));
foreach($names as $id=>$name){
$name = trim(strtolower($name));
if($name != $fname){
if(strpos($valSets[1],",") > 0){
$out[$fname][$name] = split(",",$valSets[1]);
}else{
$out[$fname][$name] = $valSets[1];
}
}
}
}else{
$name = trim($valSets[0]);
if(strpos($valSets[1],",") > 0){
$out[$name] = split(",",$valSets[1]);
}else{
$out[$name] = trim($valSets[1]);
}
}
}
}
return $out;
}
The problem I've got is that it is really limited to only two associated array elements deep. For example if I would input a string like this:
level1.level2a.level3=10::
level1.level2b=20
The output array would look like this:
Array(
[level1] => Array(
[level2a] => 10
[level3] => 10
[level2b] =>20
)
)
I'm wondering if anyone out there could help me make this a little more flexible in how it handles the associated names so that there could be more than two levels?