0

i have string like this

$string = 'root.1.child1.2.nextnode.3.anothernode.4.var';

exploded by "." and created array like this

$arr = array('root','1','child1','2','nextnode','3','anothernode','3','var');

how i can convert this array to something like this ?

it should be dynamically convert because in some cases nodes in string are in a number different with the sample .

  ["root"]=>
  array(1) {
    [1]=>
    array(1) {
      ["child1"]=>
      array(1) {
        [2]=>
        array(1) {
          ["nextnode"]=>
          array(1) {
            [3]=>
            array(1) {
              ["anothernode"]=>
              array(1) {
                [3]=>
                array(1) {
                  [var]=>
                  NULL
                }
              }
            }
          }
        }
      }
    }
  }

3 Answers 3

1

An example using recursive function.

$array = ['root', '1', 'child1', '2', 'nextnode', '3', 'anothernode', '3', 'var'];

function getNestedArray(array $arr, int $idx = 0) {
    if ($idx + 1 <= count($arr)) {
        return [$arr[$idx] => getNestedArray($arr, $idx + 1)];
    }

    return null;
}

$output = getNestedArray($array);

var_dump($output);
Sign up to request clarification or add additional context in comments.

Comments

0

This can be quit easily achieved by referencing the output and looping over the exploded array:

$output = [];
$reference = &$output;
foreach ($arr as $el) {
    if (is_numeric($el)) {
        $el = (int)$el;
    }
    $reference = [];
    $reference[$el] = null;
    $reference = &$reference[$el];
}

This also checks whether the element is a number and casts it to an integer if it is. The $output variable will contain the final array.

Comments

0

You can use recursive function

to do though


$flatArray = array('root','1','child1','2','nextnode','3','anothernode','3','var'); // your array

function createNestedArray($flatArray)
{
    if( sizeof($flatArray) == 1 ) {
        return [ $flatArray[0] => null ];  // for the case that paramter has one member we need to return [ somename => null ]
    }
    
    $nestedArray[ $flatArray[0] ] = createNestedArray(array_slice($flatArray, 1)); // otherwise we need to call createNestedArray with rest of array 
    
    return $nestedArray;
}

$nestedArray = createNestedArray($flatArray); // the result

Comments

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.