0

I am trying to create an php array elements to be nested.

For example:

I have this array:

array(3) {
  [0]=>
  string(9) "Example 1"
  [1]=>
  string(9) "Example 2"
  [2]=>
  string(9) "Example 3"
}

and I want the output to be like

array(1) {
      [0]=>
      string(9) "Example 1"
            array(1) {
              [0]=>
              string(9) "Example 2"
                  array(1) {
                    [0]=>
                    string(9) "Example 3"
                    }

I tried with foreach() but without success. Can someone help me?

Thanks.

3
  • 4
    Your output doesn't appear to make sense--there is an array and a string floating in space for each element. Do you want each element to have a single named array or a string next to an array? If the latter, should that be index 0 and 1 respectively or use some named keys? Also, when you say "output", do you actually want to transform the input array or just display it nested temporarily? Please confirm. Commented Sep 19, 2018 at 22:24
  • It would be ideal if you could show both the input and desired output arrays as actual PHP code. Commented Sep 19, 2018 at 22:29
  • can you show us how your data are represented within a php array before the output like you suggest Commented Sep 19, 2018 at 22:56

1 Answer 1

1
        $array = array("Example 1","Example 2","Example 3");



        $x = count($array) - 1;
        $temp = array();
        for($i = $x; $i >= 0; $i--)
        {
            $temp = array($array[$i] => $temp);
        }
        echo'<pre>';
        print_r($temp);

    Array
(
    [Example 1] => Array
        (
            [Example 2] => Array
                (
                    [Example 3] => Array
                        (
                        )

                )

        )

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

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.