简体   繁体   中英

php create multidimensional array from flat one

I have an array like this:

<?php
     $array = array( 0 => 'foo', 1 => 'bar', ..., x => 'foobar' );
?>

What is the fastest way to create a multidimensional array out of this, where every value is another level? So I get:

array (size=1)
 'foo' => 
   array (size=1)
    'bar' => 
      ...
      array (size=1)
        'x' => 
          array (size=1)
            0 => string 'foobar' (length=6)

Try this:

$out = array();
$cur = &$out;
foreach ($array as $value) {
    $cur[$value] = array();
    $cur = &$cur[$value];
}
$cur = null;

print_r($out);

Grabbed it from another post.

<?php
$i = count($array)-1;
$lasta = array($array[$i]);
$i--;    
while ($i>=0)
{
    $a = array();
    $a[$array[$i]] = $lasta;
    $lasta = $a;
    $i--;
}
?>

$a is the output.

What exactly are you trying to do? So many arrays of size 1 seems a bit silly.

you probably want to use foreach loop(s) with a key=>value pair

foreach ($array as $k=>$v) {
  print "key: $k  value: $v";
}

You could do something like this to achieve the array you asked for:

$newArray = array();
for ($i=count($array)-1; $i>=0; $i--) {
  $newArray = array($newArray[$i]=>$newArray);
}

I'm confused about what you want to do with non-numeric keys (ie, x in your example). But in any case using array references will help

$array = array( 0 => 'foo', 1 => 'bar',  x => 'foobar' );


$out = array();
$curr = &$out;

foreach ($array as $key => $value) {
    $curr[$value] = array(); 
    $curr = &$curr[$value];
}

print( "In: \n" );
print_r($array);
print( "Out : \n" );
print_r($out);

Prints out

In:
Array
(
    [0] => foo
    [1] => bar
    [x] => foobar
)
Out :
Array
(
    [foo] => Array
        (
            [bar] => Array
                (
                    [foobar] => Array
                        (
                        )

                )

        )

)

You can use a recursive function so that you're not iterating through the array each step. Here's such a function I wrote.

function expand_arr($arr)
{
    if (empty($arr))
        return array();

    return array(
        array_shift($arr) => expand_arr($arr)
    );
}

Your question is a little unclear since in your initial statement you're using the next value in the array as the next step down's key and then at the end of your example you're using the original key as the only key in the next step's key.

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