The essence of the question is the following - there is an array obtained by means of explode . This array can contain from 1 to 5 elements. Everything flies from space, i.e. unknown values. It is necessary to do the following - to collect a multidimensional associative array on the fly, for example:

 array(2) { [0]=> string(12) "Голова" [1]=> string(8) "Глаз" } 

How to get:

 array(1) { ["Голова"]=> array(1) { ["Глаз"]=> array(0) { } } } 

Most likely, at the next iteration of the cycle the string "Head Ear" will arrive, in the end it should turn out:

 array(1) { ["Голова"]=> array(2) { ["Глаз"]=> array(0) { } ["Ухо"]=> array(0) { } } } 

Share your advice or uncomplicated code.

  • array_flip () to help you - Edward
  • Edward, thanks for the advice, can you give me more details? this function changes the key and value in places, there is no need to do this in my task, or I do not catch up with something, the difficulty at this stage (for me) is to create an array in the array ... in the array ... in array, if necessary, from a random number of elements ... and if the beginning - i.e. 1 element of the array is already in the array, then we take this into account and push the next element further down the depth, the depth can reach 5 steps, and maybe 1! where to put your array_flip ()? 0_o - Serg
  • I did not correctly understand the essence of the problem from the first reading. - Edward

1 answer 1

Suppose you get a set of delimited strings at the input.

 $input = [ "голова", "голова/ухо", "голова/глаз/зрачок", "тело/нога", "тело/нога/колено", ]; $result = []; 

Every line you pass through explode and then build some tree body parts :)

 foreach($input as $str){ $parts = explode("/", $str); $r = &$result; foreach($parts as $p){ if(!array_key_exists($p, $r)){ $r[$p] = []; } $r = &$r[$p]; } } 

Get the reference variable, initially pointing to the array itself. Next, take the first fragment of the body. See if there is such a key in the link array or not. If not, add it. Replace the link already for this added or existing item.

 Array ( [голова] => Array ( [ухо] => Array ( ) [глаз] => Array ( [зрачок] => Array ( ) ) ) [тело] => Array ( [нога] => Array ( [колено] => Array ( ) ) ) ) 
  • YES! this is exactly what you need, the work / task is 100% completed. Many thanks! - Serg