duanaozhong0696 2015-10-19 23:23
浏览 27
已采纳

从数值数组创建类似金字塔的数组

My question is the following:

I'm looking tor an algorithm which makes $array1 look like $pyramid.

I Have this array:

$array1 = [
    'foo',
    'baz',
    'bar',
    'apple'
];

And I want to create a new array ($pyramid) from $array1 which looks like this:

$pyramid = [
    'foo' => [
        'baz' => [
            'bar' => [
                'apple' => ' '
            ]
        ]
    ]
];

The example $array1 has 4 elements, but it can be arbitrarily long, so the algorithm should work any dimension.

  • 写回答

2条回答 默认 最新

  • dpd66100 2015-10-19 23:32
    关注

    You mean something like:

    $pyramid = [];
    $pyramidPtr = &$pyramid;
    
    foreach ($array1 as $element) {
        $pyramidPtr[$element] = null;
        $pyramidPtr = &$pyramidPtr[$element];
    }
    unset($pyramidPtr);
    
    var_dump($pyramid);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?