I know http_build_query() and parse_str() are a better solution for this sort of problem but I can't change the structure of the data in the particular project I'm working on so I'm trying to simplify things a little by creating large 3d associative arrays from a database stored string.
Can someone please give me a hand making this function recursive? I want it to take something like this:
explode3D( $separators = array('|',','),
$string = "val1,val2|val1,val2,val3",
$keys = "cat1,item1,item2|cat2,item1,item2,item3"
);
And return something like this
Array (
'cat1' => Array('item1'=>'val1', 'item2'=>'val2'),
'cat2' => Array('item1'=>'val1', 'item2'=>'val2', 'item3'=>'val3')
)
Here's the function so far:
function explode3D($separators,$string,$keys=0){
$res = array();
if(is_array($separators)){//MULTI DIMENSION MODE: (unfinished!!)
//help needed here//
}else{//SINGLE DIMENSION MODE:
$vals = explode($separators,$string);
if($keys === 0){ //NO KEYS:
$res = $vals;
}else if($keys === 1){//ALTERNATE ROWS ARE KEYS:
$key = '';
for($i=0; $i<sizeof($vals); $i++){
if ($i++ % 2 == 1 ){ //every second element:
$key = $vals[$i]; //save the key
}else{
$res[$key] = $vals[$i]; //set the saved key = value
}
}
}else{ //GET KEYS FROM $keys ARRAY:
if(is_string($keys)){ //explode keys string if necessary (using $separators)
$keys = explode3D($separators,$keys);
}
for($i=0; $i<sizeof($vals); $i++){
$res[$keys[$i]] = $vals[$i];
}
}
}
return($res);
}