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(
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(
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?