1

I have this array

dev3->content->->mktg->->->pls1->->->pls2->->->config->->splash

I want to convert this string to multidimensional array. like this

 Array
        (
        [0] => dev3
        Array (
            [0] => ->content
            Array  (
                [0] => ->->mktg
                    Array(
                        [0] => ->->->pls1
                        [1] => ->->->pls2
                        [2] => ->->->config
                    )
                [1] => ->->splash
            )
        )
    )

Can anyone do this

11
  • 2
    Could we see the code you've tried to get this working? Commented Apr 28, 2016 at 10:46
  • 1
    do you need manually or pragmatically??? Commented Apr 28, 2016 at 10:50
  • 1
    the presented output is incorrect Commented Apr 28, 2016 at 10:53
  • 1
    ofcouce programatically Commented Apr 28, 2016 at 10:53
  • 1
    quite impossible, but not impossible. Commented Apr 28, 2016 at 11:02

1 Answer 1

3

it does not work if level will be increaed more then +1 on any step

$str = 'dev3->content->->mktg->->->pls1->->->pls2->->->config->->splash';

$in = preg_split('/(?<!>)(?=->)/', $str);

Above we make such array from the input string

Array
(
    [0] => dev3
    [1] => ->content
    [2] => ->->mktg
    [3] => ->->->pls1
    [4] => ->->->pls2
    [5] => ->->->config
    [6] => ->->splash
) 

continue working

$result = [];
$p = &$result;
$level = 0;
foreach($in as $i) {
  // Count next level
  $c = substr_count($i, '->');
  // if level is not changed
  if($c == $level) { $p[] = $i; continue;  } 
  // level increased
  if ($c == $level + 1) {
     $level++;
     $p[] = [$i]; 
     $p = &$p[count($p)-1];
     continue;
  }  
  // any level less then achived before
  if ($c < $level) {  
     $p = &$result;
     $level = $c;
     while($c--)
        $p = &$p[count($p)-1];
     $p[] = $i;
     continue;
  }
  die("I can't process this input string"); 
}
print_r($result);

working demo

Sign up to request clarification or add additional context in comments.

2 Comments

i did not see your comment. But i think that main idea of the code not a way to explode the string (it can be done another) but using pointer to make array. Don't you think so?
Glad to help. Good luck!

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.