0

Just working on something and can't find a simple solution to this problem without just looping through the array with a foreach. Does anyone have a simple solution for this

I want to turn this

&array(4) {
["a"]=>int(0)
["b"]=>int(1)
["c"]=>int(2)
["d"]=>int(3)
}

Into this

array(1) {
  ["a"]=>
  array(1) {
    [0]=>
    array(1) {
      ["b"]=>
      array(1) {
        [0]=>
        array(1) {
          ["c"]=>
          array(1) {
            [0]=>
            array(1) {
              ["d"]=> int(1) //this value does not matter
            }
          }
        }
      }
    }
  }
}

The values don't matter at all I just need the keys to run against a array_intersect_key_recursive function that I have.

EDIT : The array has changed after testing it needs to be nested as an array of an array

1
  • because when I built the result array I wanted i used 1 as the value. It really doesn't matter what the value is though. I will change to int(3) to make it clearer Commented Sep 18, 2012 at 23:48

2 Answers 2

1

I don't know how this could possibly end up helping you, but it was a fun exercise nonetheless.

$newArray = array();
$last = &$newArray;
$array = array_reverse(array_keys($array));
while ($item = array_pop($array)) {
   if (!is_array($last)) {
      $last = array();
   }
   $last[$item] = array(array());
   $last = &$last[$item][0];
}

NOTE: I made this answer with the int(1). You said the value is not important so I'm not going to bother changing it for now, but you would have to do a bit more work if the value was important (probably something like get the value from the original array with $item as the key).

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

Comments

0

Another approach using recursion:

function toNestedArray(array $array, $index = 0) {
    $return = array();
    if ($index < count($array)) {
        $return[$array[$index]] = toNestedArray($array, ++$index);
    }
    return $return;
}

Usage Example:

$flatArray   = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4); 
$nestedArray = toNestedArray(array_keys($flatArray));
print_r($nestedArray);

Output:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                            [d] => Array
                                (
                                )

                        )

                )

        )

)

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.