1

I have a simple array in PHP like this :

Array
(
    [max_size_video] => 50000
    [max_size_photo] => 8000
    [token_expire] => 100
    [dns] => mydns.fr
    ...
)

I want to convert this array in multidimensional width underscore as separator :

Array
(
    [max] => Array
        (
            [size] => Array
                (
                    [video] => 50000
                    [photo] => 8000
                )
        )
    [token] => Array
        (
            [expire] => 100
        )
    [dns] => mydns.fr
    ...
)

I can do this with the following uggly code :

$item = explode('_', $row);
switch (count($item)) {
  case 1:
    $array[$item[0]] = $value;
  break;
  case 2:
    $array[$item[0]][$item[1]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]] = $value;
  break;
  case 3:
    $array[$item[0]][$item[1]][$item[2]][$item[3]] = $value;
  break;
  ...
}

How can I do this with a pretty function ? Thanks for reply

3
  • 1
    Use loops or recursion. Commented Jan 26, 2021 at 17:33
  • Welcome to Stack Overflow. This site is intended for specific programming problems, working solutions that need improvement are better suited over at Code Review. Commented Jan 26, 2021 at 17:35
  • Does this answer your question? String to multidimensional/recursive array in PHP Commented Jan 26, 2021 at 17:52

1 Answer 1

0

It's pretty easy to achieve by iterating and adding branch by branch to the resulting array. Something like this.

<?php

$array = [
    'max_size_video' => 50000,
    'max_size_photo' => 8000,
    'token_expire'   => 100,
    'dns'            => 'mydns.fr',
];

$result = [];

foreach ($array as $key => $value) {
    $branch = &$result;
    foreach (explode('_', $key) as $innerValue) {
        $branch = &$branch[$innerValue];
    }
    $branch = $value;
}

var_dump($result);

The result array would look the following way.

array(3) {
  ["max"]=>
  array(1) {
    ["size"]=>
    array(2) {
      ["video"]=>
      int(50000)
      ["photo"]=>
      int(8000)
    }
  }
  ["token"]=>
  array(1) {
    ["expire"]=>
    int(100)
  }
  ["dns"]=>
  &string(8) "mydns.fr"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Juste a little problem, if I have : $array = [ 'max_size' => 10, // error in php 'max_size_video' => 50000, 'max_size_photo' => 8000, 'token_expire' => 100, 'dns' => 'mydns.fr', ];
Please update your question with a new input array and expected result. Not sure what outcome you expect out of the $array = [ 'max_size' => 10, 'max_size_video' => 50000, 'max_size_photo' => 8000, 'token_expire' => 100, 'dns' => 'mydns.fr', ];

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.