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 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上