3

I want to push some items in one array, here is the structure:

$str = 'String';
$a = array('some', 'sub', 'page');

and I want to push the items to some other array that should become:

Array (
   [some] => Array (
      [sub] => Array (
         [page] => String
      )
   )
)

I don't know how exactly to explain it, so hope the example shows you something. I want any new element in the first array (a) to be pushed as sub-array of the prevous one and the last to have the value from $str;

$string = 'My Value';
$my_first_array = array('my', 'sub', 'arrays');

Then some function to parse $my_first_array and transfer it as:

Example:

ob_start('nl2br');
$my_parsed_sub_array = parse_sub_arrays($my_first_array, $string);
print_r($my_parsed_sub_array);

===>>>

Array (
   [my] => Array (
      [sub] => Array (
         [arrays] => String
      )
   )
)
0

1 Answer 1

5

[Edit] I hope that, this time, I've understood the question...

If you have your string and array like this :

$str = 'test';
$a = array('some', 'sub', 'page');

You could first initialize the resulting array this way, dealing with that special case of the last item :

$arr = array($a[count($a)-1] => $str);

Then, you can loop over each item of your $a array, starting from the end (and not working on the last item, which we've dealt with already) :

for ($i=count($a) - 2 ; $i>=0 ; $i--) {
    $arr = array($a[$i] => $arr);
}

With this, dumping the resulting array :

var_dump($arr);

Should get you the expected result :

array
  'some' => 
    array
      'sub' => 
        array
          'page' => string 'test' (length=4)



Old answer below, before understanding the question :

You could declare your array this way :

$arr = array(
    'some' => array(
        'sub' => array(
            'page' => $str, 
        ), 
    ), 
);


Or, using several distinct steps (might be easier, depending on the way you construct your sub-arrays, especially in a more complex case than the current example) :

$sub2 = array('page' => $str);
$sub1 = array('sub' => $sub2);
$arr = array('some' => $sub1);
Sign up to request clarification or add additional context in comments.

4 Comments

No, no you don't get the point.I want to make some algorithm to parse the first array(a) to sub-arrays and the last from $a to have the value $str.I want to make this automatically via code, not manually.It complicated, sorry I can't say it better.
I'll try to explain it better in the first post, its not that.
Oh ; sorry, didn't quite understand the question :-(
@Alex I've edited my answer, hoping I've understood the question better :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.