用于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
)
)