Skip to content
Advertisement

Format simpe array in multidimensional

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
                (
                     => 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

Advertisement

Answer

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"
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement