Creating a nested parent child array from a one dimensional array in php

I have 2 arrays.

First array:

$array = array( 'a' => 'b', 'b' => 'c', 'c' => 'd', ); 

Second array:

  $array = Array ( [a] => Array ( [0] => b [1] => h ) [b] => c [c] => d [h] => m ) 

I need to change this array, for example

First array:

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

Second array:

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

Sirwilliam's answers helped solve the problem with the first array. and I need it for a multidimensional array. Help solve the problem. thanks in advance

+7
arrays php
source share
1 answer

You can try using and (links):

PHP:

  $array = array( 'a' => 'b', 'b' => 'c', 'c' => 'd', ); $newArray = array(); $newArray[key($array)] = array(); $part = &$newArray; foreach($array as $first => $second){ $part = &$part[$first]; $part[$second] = array(); } echo "<pre>"; print_r($newArray); echo "</pre>"; ?> 

Result:

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

Then you can create a loop for the last part.

+6
source share