Convert associative array to multidimensional array with value

This is an interesting situation in which I created a working function, but I wonder if I only have something simpler methods for this.

I have the following multidimensional array:

$foo = array( [0] => array( 'keys' => array( 'key1' => 1, 'key2' => a, 'key3' => 123 ), 'values' => array( //goodies in here ) ) [1] => array( 'keys' => array( 'key1' => 1, 'key2' => b, 'key3' => 456 ), 'values' => array( //goodies in here ) ) ) 

I wanted to convert this to a multidimensional array, nested based on the values from the keys array, the result I was looking for is this:

 $bar = array( [1] => array( [a] => array( [123] => array( //values array from above ) ), [b] => array( [456] => array( //values array from above ) ) ) ) 

Keys can always be nested depending on their position in the keys array, but themselve keys are not always the same, keys processes a user-defined grouping, so the order and values ​​can change. I also did not want to duplicate the keys.

I did not succeed with array_merge , because in many cases the keys of the array are actually numeric identifiers. So this function works, but I wonder if I made myself a new pair of gloves .

  protected function convertAssociativeToMulti( &$output, $keys, $value ) { $temp = array(); $v = array_values( $keys ); $s = sizeof( $v ); for( $x = 0; $x < $s; $x++ ) { $k = $v[ $x ]; if ( $x == 0 ) { if ( !array_key_exists( $k, $output ) ) $output[ $k ] = array(); $temp =& $output[ $k ]; } if ( $x && ( $x + 1 ) !== $s ) { if( !array_key_exists( $k, $temp ) ) $temp[ $k ] = array(); $temp =& $temp[$k]; } if ( ( $x + 1 ) == $s ) $temp[$k] = $value; } } $baz = array(); foreach( $foo as $bar ) { $this->convertAssociativeToMulti( $baz, $bar['keys'], $bar['values'] ); } 

So how do you make it easier / refactor what I have?

+6
source share
1 answer

This is a bit more concise (see it in action here ):

 $bar=array(); foreach($foo as $item) { $out=&$bar; foreach($item['keys'] as $key) { if(!isset($out[$key])) $out[$key]=array(); $out=&$out[$key]; } foreach($item['values'] as $k=>$v) $out[$k]=$v; // $out=array_merge($out,$item['values']); -- edit - fixed array_merge } var_dump($bar); 
+3
source

All Articles