Skip to content

array_flatten_into_dots

Tonya Mork edited this page Mar 12, 2017 · 2 revisions
array_flatten_into_dots()

The array_flatten_into_dots() function flattens a multi-dimensional array into one single level with the keys compressed into dot notation to indicate each depth level. If you want to prefix the keys, just pass in the prefix as the second argument.

Uses Dot Notation?

Yes. It returns a flatten array in dot notation.

Syntax

array array_flatten_into_dots( 
     array array $subjectArray, 
     [ string $keyPrefix = '' ]
);

where:

$subjectArray is the array to work on and flatten

$keyPrefix (optional) When supplied, each of the keys is prefixed with the value you specify.

Examples

$user     = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@bobjones',
		'website' => array(
			'personal' => 'https://bobjones.com',
			'business' => 'https://foo.com',
		),
	),
);

$user = array_flatten_into_dots( $user );
/**
array(
	'user_id'                  => 504,
	'name'                     => 'Bob Jones',
	'social.twitter'           => '@bobjones',
	'social.website.personal'  => 'https://bobjones.com',
	'social.website.business'  => 'https://foo.com',
);
*/   

Example - Prefix

Want a prefix added to the keys? Just pass it as the 2nd parameter. Example:

$user     = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@bobjones',
		'website' => array(
			'personal' => 'https://bobjones.com',
			'business' => 'https://foo.com',
		),
	),
);

$user = array_flatten_into_dots( $user );
/**
array(
	'user_id'                  => 504,
	'name'                     => 'Bob Jones',
	'social.twitter'           => '@bobjones',
	'social.website.personal'  => 'https://bobjones.com',
	'social.website.business'  => 'https://foo.com',
);
*/   

« Back to Array API

Clone this wiki locally