重新格式化关联数组

时间:2011-09-24 07:26:49

标签: php arrays associative-array

更具体地说,我想将以下数组转换为关联数组。原始数组的索引类似于[0],[1],[2],... [n]。我使用的函数是Cakephp的 Set :: combine ,但我无法重新创建所需的关联数组的所有三个级别。

Array
(
    [0] => Array
        (
            [ACCOUNTS] => Array
                (
                    [description] => A
                )

            [HEADERS] => Array
                (
                    [description] => B                
                )

            [COLUMNS] => Array
                (
                    [description] => C
                    [id] => 8
                )

        )
    [1] => Array
        (
            [ACCOUNTS] => Array
                (
                    [description] => A1
                )

            [HEADERS] => Array
                (
                    [description] => B1                
                )

            [COLUMNS] => Array
                (
                    [description] => C1
                    [id] => 9
                )

        )       
)

我想要结束的数组是以下关联数组:

Array
(
    [A] => Array
        (
            [B] => Array
                (
                    [C] => 8
                )
        )
    [A1] => Array
        (
            [B1] => Array
                (
                    [C1] => 9
                )
        )       
)

我无法重新创建上面数组的所有(3)级别。

1 个答案:

答案 0 :(得分:0)

你的意思是:

$newarray = array($first['ACCOUNTS']['description'] => array($first['HEADERS']['description']  => array($first['COLUMNS']['description'] => $first['COLUMNS']['id'])));

因此,如果您运行以下内容,它会提供您想要的内容:

$first = array(
 'ACCOUNTS' => array('description' => 'A'),
 'HEADERS' => array('description' => 'B'), 
 'COLUMNS' => array('description' => 'C', 'id' => '8'));

echo "<pre>";
print_r($first);


$newarray = array($first['ACCOUNTS']['description'] =>
            array($first['HEADERS']['description']  =>  
                array($first['COLUMNS']['description'] =>
                    $first['COLUMNS']['id'])));


print_r($newarray);

然后你最终得到:

Array
(
    [ACCOUNTS] => Array
        (
            [description] => A
        )

    [HEADERS] => Array
        (
            [description] => B
        )

    [COLUMNS] => Array
        (
            [description] => C
            [id] => 8
        )

)
Array
(
    [A] => Array
        (
            [B] => Array
                (
                    [C] => 8
                )

        )

)