これを行うために使用parse_str
します。以下を試してください。
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
function unflatten($array,$prefix = '')
{
$result = array();
foreach($array as $key=>$value)
{
if(!empty($prefix))
{
$key = preg_replace('#^'.preg_quote($prefix).'#','',$key);
}
if(strpos($key,'.') !== false)
{
parse_str('result['.str_replace('.','][',$key)."]=".$value);
}
else $result[$key] = $value;
}
return $result;
}
$source = array('a'=>'d','b',array('a'=>'c','d'));
$flattened = flatten($source,'__');
echo "<pre>";
echo "source array :<br/>";
print_r($source);
echo "flatten result:<br/>";
print_r($flattened);
echo "unflatten result:<br/>";
print_r(unflatten($flattened,'__'));
echo "<pre/>";
出力:
source array :
Array
(
[a] => d
[0] => b
[1] => Array
(
[a] => c
[0] => d
)
)
flatten result:
Array
(
[__a] => d
[__0] => b
[__1.a] => c
[__1.0] => d
)
unflatten result:
Array
(
[a] => d
[0] => b
[1] => Array
(
[a] => c
[0] => d
)
)