2

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; 
}
9
  • you've to use recursive function. did you try something? Commented Jul 28, 2018 at 11:29
  • No i don't use some function Commented Jul 28, 2018 at 11:30
  • I add than recursion function if i help you, but it is not do the job. This is only for replaceing Commented Jul 28, 2018 at 11:34
  • you set $key as array key but you told us that you want to set $value. Commented Jul 28, 2018 at 11:35
  • What functions can you use? you mentioned count, can you use array_shift? Commented Jul 28, 2018 at 12:17

4 Answers 4

2

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
                        )
                )
        )
)
Sign up to request clarification or add additional context in comments.

2 Comments

This is not autonomous ...$values
In what way does having a function parameter make it not autonomous?
1

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"
      }
    }
  }
}

8 Comments

This is not autonomous function it is using "array_slice" function! The "count" function is ok but not the "array_slice"
Lemme fix that.
This is not autonomous, you are using the for statement.
Do not using reference at all!
So using return also counts? And by references you mean if and return?
|
1
$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;

4 Comments

That's cheating as it relies on knowing the length of the array is 5. You should use count to get the length of the array.
No i know the count before i call the function!
But what if you had to process a different array? You would need to change the code. My answer and @OluwafemiSule don't rely on knowing the length of the array.
This is nice question! I use different arrays outside of this function like $single = to_multidimentional($single, count($array)); I update my answer
0

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 ];
    }
}

9 Comments

this does not solve his problem. Each iteration you erase $multidimensional.
Nice answer but it's not autonomous you are using the for statement i need something 100% autonomous and with function
it will give E_NOTICE : type 8 -- Undefined variable: multidimensional
@JohnStamoutsos but he gave you part of the solution, you've to iterate the array backwards.
@AlexandrePainchaud Painchaud This is a nice answer but you can make it inside the function and without the for statement?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.