0

我有一个像这样的数组:

Array
{
   'property1.subproberty11' => "xxxxx",
   'property1.subproberty12' => "yyyy",
   'property2.subproberty21.subproperty211' => "zzzzzz",
   'property2.subproberty21.subproperty212' => "wwwww",
   'property2.subproberty22' => "yyyy",
   ....

这需要更改为:

Array
(
[property1] => Array
    (
            ['subproberty11'] => "xxxxx"
            ['subproberty12'] => "yyyy"
    )

[property2] => Array
    (
        [subproperty21] => Array
            (
                [subproperty211] => "zzzzzz"
                [subproperty212] => "wwwwww"
            )
        ['subproberty22'] => "yyyy"

    )
   ...

我找不到这样做的聪明方法,有人可以帮助我吗?

所以,到目前为止,我已经想到了这种算法:

$new_array = array();
foreach($old_array as $key => $value)
{
    $subkeys = explode('.', $key);
    $ss = array();
    for($ii = 0 ; $ii < count($subkeys) ; $ii++)
    {
        $ss[] = "['".$subkeys[$ii]."']";
        if ($ii < count($subkeys) -1)
            eval('$new_array'.implode('',$ss).' = array();');
    }
    eval('$new_array'.implode('',$ss)." = '".$value."';');
}

我认为我们可以做得更好,例如也许我们可以通过创建一个新数组来避免重复数据?

4

2 回答 2

0

一些未经测试的代码,为您提供可以采取的方向。

只需遍历数组;

function SplitArray($properties) {
    foreach($properties as $item=>$property) {
        $properties[$item] = explode('.',$property, 2);
        if(strpos($properties[$item][1], '.') === false)) {}
        else {
            $properties[$item][1] = SplitArray($properties[$item][1]);
        }
    }
    return $properties;
}
于 2013-10-20T12:08:59.100 回答
0

我的工作示例:

function nestedKeysArray($input) {
    $array = array();
    foreach ($input as $key => $value) {
        $keys = explode('.', $key);
        if (count($keys) == 1) {
            $array[$key] = $value;
        } else {
            $nested = &$array;
            foreach ($keys as $k) {
                if (!isset($nested[$k]))
                    $nested[$k] = array();
                $nested = &$nested[$k];
            }
            $nested = $value;
        }
    }
    return $array;
}

$input 是问题中的第一个数组。

编辑: 更改原始数组,不复制:

function nestedKeysArray(&$input) {
    foreach ($input as $key => $value) {
        $keys = explode('.', $key);
        if (count($keys) > 1) {
            $nested = &$input;
            foreach ($keys as $k) {
                if (!isset($nested[$k]))
                    $nested[$k] = array();
                $nested = &$nested[$k];
            }
            $nested = $value;
            unset($input[$key]);
        }
    }
}
于 2013-10-20T12:47:23.587 回答