<?php

function keyExistsInAll($key, $sections)
{
	$sections = (array) $sections;
	unset($sections['basic']);
	foreach ($sections as $section => $data) {
		$data = (array) $data;
		if (!isset($data[$key])) {
			return false;
		}
	}

	return true;
}

function buildIni($sections)
{
	$out = '';
	$common = array();
	$sections = (array) $sections;
	foreach ($sections as $section => $data) {
		$out .= "[$section]\n";
		foreach ($data as $key => $value) {
			if (!keyExistsInAll($key, $sections)) {
				foreach ($value as $sub => $value) {
					if (is_array($value)) {
						foreach ($value as $value) {
							$out .= "$key.{$sub}[] = '$value'\n";
						}
					} elseif (is_object($value)) {
						foreach ($value as $k => $value) {
							$out .= "$key.$sub.$k = '$value'\n";
						}
					} else {
						$out .= "$key.$sub = '$value'\n";
					}
				}
				$out .= "\n";
			} else {
				$common[$key] = $value;
			}
		}
	}

	if (!isset($sections['common']) && !empty($common)) {
		$out = buildIni(array('common' => $common)) . $out;
	}

	return $out;
}
