How to convert one dimensional array to two dimensional array

I have the following array coming from a form with multilingual data like this:

Array
(
    [en_name] => ...........
    [en_description] => ...........
    [gr_name] => ...........
    [gr_description] => ...........
)

      

How can this array be converted to two-dimensional, for example:

Array
(
    [en] => Array
        (
            [name] => ...........
            [description] => ...........
        )

    [gr] => Array
        (
            [name] => ...........
            [description] => ...........
        )
)

      

+3


source to share


3 answers


Use this code:



$finalArr = array();
foreach($arr as $key => $val) {
   $tok = explode('_', $key);
   $finalArr[$tok[0]][$tok[1]] = $val;
}

      

+4


source


Try to run



$output = array();
foreach($arr as $val){
            $prefix = str_replace("_","",substr($val,0,3));
            $ending = substr($val,3,strlen($val));
            if(!is_array($output[$prefix]))
                 $output[$prefix] = array();
            array_push($output[$prefix],$ending);    
        }

      

+1


source


$array3d = array();
foreach($arr as $key => $value) {
    $keyArr = explode("_", $key);
    $array3d[$keyArr[0]][$keyArr[1]] = $value;
}

      

This should work as long as each key has only one underscore.

+1


source







All Articles