简体   繁体   中英

PHP how to convert an single array to multidimentional array?

I have that single array and I need to convert in a multidimensional array without using array_merge , array_replace_recurcive etc, just an autonomous function:

$single = [
    0 => 'one',
    1 => 'two',
    2 => 'tree',
    3 => 'four',
    4 => 'five'
];

And convert to look like this, with the last key as value:

$multidimentional = [
    'one' => [
        'two' => [
            'tree' => [
                'four' => 'five'
            ]
        ]
    ]
];

I have create a recursion function if this helps:

function array_replace_recursive($defaults, $replaces) {

    if(is_null($replaces)) {
        $replaces = [];
    }

    if(!is_array($defaults) || !is_array($replaces)) {
        return $replaces;
    }

    foreach($defaults as $key => $value) {
        if(!array_key_exists($key, $replaces) || is_null($replaces[$key])) {
            $replaces[$key] = $value;
        } else {
            if(is_array($replaces[$key]) && is_array($value)) {
                $replaces[$key] = array_replace_recursive($replaces[$key], $value);
            }
        }
    }

    return $replaces; 
}

You can do this with PHP (as of 5.6) argument unpacking and a very simple recursive function:

$single = [
    0 => 'one',
    1 => 'two',
    2 => 'tree',
    3 => 'four',
    4 => 'five'
];

function convert($key, ...$values) {
    if (count($values) == 1)
        return array($key => $values[0]);
    else
        return array($key => convert(...$values));
}

print_r(convert(...$single));

Output:

Array
(
    [one] => Array
        (
            [two] => Array
                (
                    [tree] => Array
                        (
                            [four] => five
                        )
                )
        )
)

You can also do it without using count (only isset ):

function convert2($key, ...$values) {
    if (!isset($values[1]))
        return array($key => $values[0]);
    else
        return array($key => convert(...$values));
}

print_r(convert2(...$single));

Output:

Array
(
    [one] => Array
        (
            [two] => Array
                (
                    [tree] => Array
                        (
                            [four] => five
                        )
                )
        )
)

Thinking in recursion, you can write a base case that returns the value of the currently seen item if it is one less than the length of the array.

$singleDim = [
    0 => 'one',
    1 => 'two',
    2 => 'tree',
    3 => 'four',
    4 => 'five'
];

function toMultiDimArray($arr, $seen=0) {
    if ([] === $arr) {
        return [];
    }

    if(count($arr) - 1 === $seen) {
        return $arr[$seen];
    }

    return [
       $arr[$seen] => toMultiDimArray($arr, $seen+1)
    ];
}

$multiDim = toMultiDimArray($singleDim);

var_dump($multiDim);

array(1) {
  ["one"]=>
  array(1) {
    ["two"]=>
    array(1) {
      ["tree"]=>
      array(1) {
        ["four"]=>
        string(4) "five"
      }
    }
  }
}
$single = [
    0 => 'one',
    1 => 'two',
    2 => 'tree',
    3 => 'four',
    4 => 'five'
];

function to_multidimentional($array, $count = 0, $seen = 0) {

    if($count - 1 === $seen) {
        return $array[$seen];
    }

    return [
       $array[$seen] => to_multidimentional($array, $count, $seen + 1)
    ];
}

$single = to_multidimentional($single, count($single));

print_r($single);

exit;

There's nothing recursive about this. It's just iterating over the $single array backwards and then embedding the result inside the new key each time:

function foo( $single ) {
    $multidimensional = [ $single[ count($single) - 1 ] ];

    for( $i = count($single) - 2; $i >= 0; $i--  ) {
      $multidimensional = [ $single[$i] => $multidimensional ];
    }
}

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