dtkwt62022 2018-07-28 03: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 03: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部