Convert a one-dimensional array to a multidimensional linked array

I have me at a standstill. I searched and found similar questions, but I cannot find any questions that would fit my exact problem.

In PHP, I have an array like this:

<?php $array = array('one', 'two', 'three', 'four'); ?> 

I want to convert this to a multidimensional array as follows:

 <?php $new_array = array('one' => array('two' => array('three' => array('four' => NULL)))); // or, to put another way: $new_array['one']['two']['three']['four'] = NULL; ?> 

Bearing in mind, I don’t know how many elements will be in the original array, I need a way to recursively create a multidimensional linked array.

It seemed like easy to do, but I can't figure it out.

+4
source share
2 answers

You can easily do this with links:

 $out = array(); $cur = &$out; foreach ($array as $value) { $cur[$value] = array(); $cur = &$cur[$value]; } $cur = null; 

Printing $out should give you:

 Array ( [one] => Array ( [two] => Array ( [three] => Array ( [four] => ) ) ) ) 
+5
source
 function recursive_array_convert ($input, &$result = array()) { $thisLevel = array_shift($input); if (count($input)) { if (!isset($result[$thisLevel]) || !is_array($result[$thisLevel])) { $result[$thisLevel] = array(); } recursive_array_convert($input, $result[$thisLevel]); } else { $result[$thisLevel] = NULL; } return $result; } 

This function should give you more flexibility - you can just pass the input array to the first argument and catch the result in the return, or you can pass the existing variable in the second argument so that it fills the result, This means that you can achieve what you want in your example:

 $result = recursive_array_convert(array('one', 'two', 'three', 'four')); 

... or...

 recursive_array_convert(array('one', 'two', 'three', 'four'), $result); 

At first glance it may seem insignificant in this option, but pay attention to the following:

 $result = array(); recursive_array_convert(array('one', 'two', 'three', 'four'), $result); recursive_array_convert(array('five', 'six', 'seven', 'eight'), $result); print_r($result); /* Output: Array ( [one] => Array ( [two] => Array ( [three] => Array ( [four] => ) ) ) [five] => Array ( [six] => Array ( [seven] => Array ( [eight] => ) ) ) ) */ 

As you can see, this function can be used to create whole chains, as you like in the same variable.

+1
source

Source: https://habr.com/ru/post/1392250/


All Articles