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

Lokomass
  • 41
  • 6
  • 1
    Use loops or recursion. – Barmar Jan 26 '21 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](https://codereview.stackexchange.com/). – El_Vanja Jan 26 '21 at 17:35
  • Does this answer your question? [String to multidimensional/recursive array in PHP](https://stackoverflow.com/questions/49563864/string-to-multidimensional-recursive-array-in-php) – Syscall Jan 26 '21 at 17:52

1 Answers1

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"
}
Mikhail Prosalov
  • 4,155
  • 4
  • 29
  • 41
  • 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', ]; – Lokomass Jan 27 '21 at 08:51
  • 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', ];` – Mikhail Prosalov Jan 27 '21 at 09:38