[ create a new paste ] login | about

Link: http://codepad.org/WOBFMo4r    [ raw code | output | fork ]

PHP, pasted on Feb 23:
<?php
/**
 * @link http://stackoverflow.com/questions/9416661/php-multidimensional-array-to-simple-array
 */


$array = array(
    'one' => 'one_value',
    'two' => array
        (
            'four' => 'four_value',
            'five' => 'five_value'
        ),

    'three' => array
        (
            'six' => array
                (
                    'seven' => 'seven_value'
                )

        )
);

$separator = '-';
$flat = array();

do
{
	$key = key($array);
	$value = array_shift($array);
	if (is_array($value))
	{
		foreach($value as $subKey => $node)
		{
			if ( FALSE !== strpos($subKey, $separator))
			{
				throw new RuntimeException(sprintf('Key %s can not contain %s.', $subKey, $separator));
			}
			$array[$key.$separator.$subKey] = $node;
		}
	}
	else
	{
		$flat[$key] = $value;
	}
}
while($array);

print_r($flat);


Output:
1
2
3
4
5
6
7
Array
(
    [one] => one_value
    [two-four] => four_value
    [two-five] => five_value
    [three-six-seven] => seven_value
)


Create a new paste based on this one


Comments: