7

Say, we have an array: array(1,2,3,4,...) And I want to convert it to:

array(
    1=>array(
        2=>array(
            3=>array(
                4=>array()
            )
        )
    )
)

Can anybody help?
Thanks

EDIT It would be good to have the solution with iterations.

5
  • 2
    Sounds a little bit unlogical. What do you need it for? Commented Jun 19, 2013 at 10:40
  • 2
    Q. How to make something out of an array? A. Use a loop. Commented Jun 19, 2013 at 10:41
  • Care to share with us why you want to do this? It's hard to imagine any case that you would need it. Commented Jun 19, 2013 at 10:41
  • I'm learning php and want to practice with arrays. Commented Jun 19, 2013 at 10:44
  • 1
    @YourCommonSense or sometimes even better, a recursive function.. Commented Jun 19, 2013 at 11:10

5 Answers 5

12
$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
    $temp = array($array[$i] => $temp);
}
Sign up to request clarification or add additional context in comments.

Comments

9

You can simply make a recursive function :

<?php
function nestArray($myArray)
{
    if (empty($myArray))
    {
        return array();
    }

    $firstValue = array_shift($myArray);
    return array($firstValue => nestArray($myArray));
}
?>

4 Comments

I think this is the clearest solution, can tell what it does just by glancing at it. You should probably return an empty array in the base case.
Yes, this might be an elegant solution but I needed iterative one. Thanks for your help :). So many ways of accomplishing the same task.
@MrFix : The mental process one can use to construct your array is clearly recursive (as often with nested tasks), and this solution has the advantage to be clear and concise. If you're goal is to practice, you'd better take the good habits right now :-) .
@Blackhole, I'm learning step by step and I think it would be good for me to learn other possible solutions as well. Thanks for your suggestions :)
8

Well, try something like this:

$in  = array(1,2,3,4); // Array with incoming params
$res = array();        // Array where we will write result
$t   = &$res;          // Link to first level
foreach ($in as $k) {  // Walk through source array
  if (empty($t[$k])) { // Check if current level has required key
    $t[$k] = array();  // If does not, create empty array there
    $t = &$t[$k];      // And link to it now. So each time it is link to deepest level.
  }
}
unset($t); // Drop link to last (most deep) level
var_dump($res);
die();

Output:

array(1) {
  [1]=> array(1) {
    [2]=> array(1) {
      [3]=> array(1) {
        [4]=> array(0) {
        }
      }
    } 
  }
} 

Comments

3

I think the syntax for the multidimensional array you want to create would look like the following.

$array = array(

   'array1' => array('value' => 'another_value'), 
   'array2' => array('something', 'something else'),
   'array3' => array('value', 'value')
);

Is this what you're looking for?

2 Comments

Why in the world is this answer upvoted?!? It doesn't provide any converting code at all.
This is the answer that finally helped me understand how to do what I was trying to do. It clicked when I read this one.
1

You can also use this array library to do that in just one line:

$array = Arr::setNestedElement([], '1.2.3.4', 'value');

1 Comment

...obviously this is not the sample input (not that it would be difficult to convert to the OP's data type)

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.