Skip to content

Instantly share code, notes, and snippets.

@richjenks
Last active August 29, 2015 14:13
Show Gist options
  • Save richjenks/75b715bcb728290096ea to your computer and use it in GitHub Desktop.
Save richjenks/75b715bcb728290096ea to your computer and use it in GitHub Desktop.
Flatten array and convert $_POST array into the HTML names that would create it
/**
* post2name
*
* Converts a $_POST array to a flat array of the form element `name`s which would have produced it.
*
* For example, the PHP array:
*
* 'foo' => 'bar',
* 'baz' => [
* 'foo' => 'bar',
* ],
*
* would turn into:
*
* 'foo' => 'bar',
* 'baz[foo]' => 'bar',
*
* @param array $array Array to be converted
* @return array Flat array of HTML `name`s
*/
function post2name( $array ) {
$result = array();
$array = flatten_array( $array );
foreach ( $array as $key => $value ) {
$parts = explode( '.', $key );
$i = 0;
$new_key = '';
foreach ( $parts as $part ) {
if ( $i !== 0 ) $part = '[' . $part . ']';
$new_key .= $part;
$i++;
}
$i = 0;
$result[ $new_key ] = $value;
}
return $result;
}
/**
* flatten_array
*
* Turns a multi-dimensional array into a flat one separated by dots
*
* @param array $array Array to be flattened
* @param string $prefix Received previous value from recursive call
*
* @return array Flat array
*/
function flatten_array( $array, $prefix = '' ) {
$result = array();
foreach( $array as $key => $value ) {
if ( is_array( $value ) ) {
$result = $result + flatten_array( $value, $prefix . $key . '.' );
} else {
$result[ $prefix . $key ] = $value;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment