String to Array variable split

tonelm54
tonelm54 used Ask the Experts™
on
Ive been struggeling with an issue for a while of turning a string into an array, but a multi dimentinal array. So for example:-

$sett["Settings.General.View.Scheme"] = 12;
$sett["Settings.General.IDE.Color"] = 15;
$sett["Settings.General"] = "Allowed";
to turn into

$sett["Settings"].["General"].["View"].["Scheme"] = 12;
$sett["Settings"].["General"].["IDE"].["Color"] = 15;
$sett["Settings"].["General"] = "Allowed";

Ive played around trying to get it to work with functions and for loops but cant get it working. Any ideas or pointers?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
<?php
// Some sample data
$sett["Settings.General.View.Scheme"] = 12;
$sett["Settings.General.IDE.Color"] = 15;
$sett["Settings.General"] = "Allowed";

// Where we will store the new array
$result = [];

// Iterate over the source array getting key and values
foreach($sett as $k => $v) {

  // Explode the key into its parts
  $keys = explode('.', $k);
  addToArray($result, $v, $keys);
}

print_r($result);

// Workhorse. We pass the target by reference so that changes are made
// to the incoming array and not a copy
function addToArray(&$target, $val, $keys) {
  // Set a marker to the reference of the incoming array so we are dealing with the actual array
  $current = &$target;

  // For each key check if that key exists in this level of the array and if not add it as a new empty array
  foreach($keys as $k) {
    if (!isset($current[$k])) {
      $current[$k] = [];
    }

    // Set our current marker to the current node in the heirarchy
    $current = &$current[$k];
  }

  // When we get here we will be at the "bottom" of the node hierarchy - so set the value
  $current[] = $val;

  // No need to return anything as we are working on a reference to the target array
}

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@tonelm54

Regarding your comment in the testimonial - I have added comments to the code in case you have not seen them, that explain how the code works.

If you are stuck - feel free to post back with questions.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial