dtkwt62022 2018-07-28 11:24
浏览 69
已采纳

PHP如何将单个数组转换为多维数组?

I have that single array and I need to convert in a multidimensional array without using array_merge, array_replace_recurcive etc, just an autonomous function:

$single = [
    0 => 'one',
    1 => 'two',
    2 => 'tree',
    3 => 'four',
    4 => 'five'
];

And convert to look like this, with the last key as value:

$multidimentional = [
    'one' => [
        'two' => [
            'tree' => [
                'four' => 'five'
            ]
        ]
    ]
];

I have create a recursion function if this helps:

function array_replace_recursive($defaults, $replaces) {

    if(is_null($replaces)) {
        $replaces = [];
    }

    if(!is_array($defaults) || !is_array($replaces)) {
        return $replaces;
    }

    foreach($defaults as $key => $value) {
        if(!array_key_exists($key, $replaces) || is_null($replaces[$key])) {
            $replaces[$key] = $value;
        } else {
            if(is_array($replaces[$key]) && is_array($value)) {
                $replaces[$key] = array_replace_recursive($replaces[$key], $value);
            }
        }
    }

    return $replaces; 
}
  • 写回答

4条回答 默认 最新

  • doukong9982 2018-07-28 11:53
    关注

    Thinking in recursion, you can write a base case that returns the value of the currently seen item if it is one less than the length of the array.

    $singleDim = [
        0 => 'one',
        1 => 'two',
        2 => 'tree',
        3 => 'four',
        4 => 'five'
    ];
    
    function toMultiDimArray($arr, $seen=0) {
        if ([] === $arr) {
            return [];
        }
    
        if(count($arr) - 1 === $seen) {
            return $arr[$seen];
        }
    
        return [
           $arr[$seen] => toMultiDimArray($arr, $seen+1)
        ];
    }
    
    $multiDim = toMultiDimArray($singleDim);
    
    var_dump($multiDim);
    
    array(1) {
      ["one"]=>
      array(1) {
        ["two"]=>
        array(1) {
          ["tree"]=>
          array(1) {
            ["four"]=>
            string(4) "five"
          }
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器