duanaozhong0696 2015-10-20 07: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-20 07:32
    关注

    You mean something like:

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

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键