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

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 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?
  • ¥50 复现论文;matlab代码编写