简体   繁体   中英

How to convert an 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 into a two dimensional like:

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

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

Use this code:

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

Try the following

$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);    
        }
$array3d = array();
foreach($arr as $key => $value) {
    $keyArr = explode("_", $key);
    $array3d[$keyArr[0]][$keyArr[1]] = $value;
}

That should work provided that each key only has 1 underscore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM