sunebrodersen
sunebrodersen

Reputation: 309

Convert one level array to multilevel array in php

I have an array and a var like this:

$arrPs =array('p1','p2','pN');
$intVar = 80;

Now i want to convert it into an array like this:

array(
   'p1'=>array(
            'p2'=>array(
                'pN'=>$intVar
             )
     )
);

This should work no matter how many values are in $arrPs array.

Hope this makes sense.

/Sune

Upvotes: 0

Views: 171

Answers (4)

Ashish
Ashish

Reputation: 68

$arrPs = array('p1','p2','pN');
$intVar = 80;

$new_array = array();
$counter   = 1; 
for( $i = count($arrPs); $i >= 0; $i-- )
{
  if( $counter==1)
  {
    $new_array = $intVar;
  }
  else
  {
    $new_array = array( $arrPs[$i] => $new_array);
  }

  $counter++;
}

print_r($new_array);

Upvotes: 0

ajreal
ajreal

Reputation: 47321

eval is good for this, use it with your own risk, and if the data is trustable

eval ('$rtn[\''.implode("']['", $arrPs).'\']='.$intVar.';');
var_dump($rtn);

Upvotes: 1

Stephen
Stephen

Reputation: 18917

function myWalker($input, $last, &$output = array()) {
    if (count($input) > 1) {
        $val = array_shift($input);
        $output[$val] = array();
        myWalker($input, $last, $output[$val]);
    }
    else {
        $output[$input[0]] = $last;
    }

    return $output;
}

$out = myWalker($arrPs, $intVar);

Upvotes: 4

Kel
Kel

Reputation: 7780

I'd suggest something like this:

function buildNestedArrays($array, $initVar) {
    $current = current($array);
    $next = next($array);
    if ($next === FALSE) {
        return array($current => $initVar);
    } else {
        return array($current => buildNestedArrays($array, $initVar));
    }
}

Usage:

reset($arrPs);
print_r(buildNestedArrays($arrPs, $intVar));

Upvotes: 0

Related Questions