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 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密