4

我正在使用以下函数来展平多维数组:

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;
}

我想创建一个匹配函数,unflatten它将反转该过程(例如,如果键中有 a .,则创建一个子数组)。有任何想法吗?

4

1 回答 1

8

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

)
于 2012-07-17T08:44:09.560 回答