Convert multi-dimensional array to easily parsable string

Flattens array entries so that they can be parsed and/or read easily. I use this in CrossORM to make the permission definitions easy to read and write by users.

function flatten_array($array, $parents = '')
{
	if ( !is_array($array) AND !is_object($array))
	{
		return array($parents . $array);
	}

	$array  = (array) $array;
	$flat 	= array();

	foreach ($array AS $k => $v)
	{
		if (is_numeric($k))
		{
			$k = '';
			$p = $parents;
		} else
		{
			$p = $parents . $k . '.';
			$flat[] = $parents . $k;
		}

		$flat = array_merge($flat,flatten_array($v,$p));
	}

	return $flat;
}

Sample usage:

$array = flatten_array(array(
	"fruits"  	=> array(
		"a" 		=> "orange",
        "b" 		=> "banana",
        "c" 		=> "apple"
    ),
    "numbers" 	=> array (
		1, 2, 3, 4, 5, 6
	),
    "holes"   	=> array (
		"first",
        5 			=> "second",
        "third"
    )
));

echo implode('\n',$array);

Produces:

fruits
fruits.a
fruits.a.orange
fruits.b
fruits.b.banana
fruits.c
fruits.c.apple
numbers
numbers.1
numbers.2
numbers.3
numbers.4
numbers.5
numbers.6
holes
holes.first
holes.second
holes.third

There is no additional info about this author.
There are no comment yet. Be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>