Search code examples
phparraysvectoriterationcycle

Adding elements to array as sub-elements dynamically in PHP


I want to find a workaround for the following problem:

I have n vectors(unique), like the following: ("val1", "val2", "val3", ..., "valn" ). Each vector's length is different.

I want to add any of those in a new array, but using the vector values(val1,val2,val3) elements as sub-elements recursively for the new array, taken from the main vector(val1 => val+1 => val+2 => val+3 => ... val+n => solution), and the last element of the vector is an integer or a string(not a sub-array/vector as the others), which will match with the last element of the new array, and it's new array's soluton/target.

The workaround solution I am applying right now is this: Let's suppose the target(solution) is the end value of the array(an integer or string). In this case I suppose to work on a vector with 4 elements, where the last one is the solution.

$vector = array("val1", "val2", "val3", "target");
$count = count($vector);
$new_array = array();
switch($count){
case 1:
....
case 4:
$new_array[$vector[0]][$vector[1]][$vector[2]] = $vector[3];
/*New array will be
$new_array = [
val1 => 
  val2 => 
    val3 => "target"
];
*/
break;
}

The vectors I am using are many and with different sizes, so the solution/target can be in the 1st element, second, third and so on, so I applied in my switch any cases from 0 to 5 for example, working as wrote above.

I think there could be a better solution, to loop inside a for(or better, a while) cycle But I am currently having no ideas on how it should be, and I didn't find any workaround in the web.

Does anyone have a soluton for this? Thanks in advance


Solution

  • You can build the resulting array starting from the most recent nested element:

    $vector = array("val1", "val2", "val3", "val4", "val5", "target");
    
    $new_array = array_pop($vector);
    
    foreach(array_reverse($vector) as $val) {
        $new_array = [$val => $new_array];
    }
    
    print_r($new_array);