dqotv26286 2011-11-03 23:03
浏览 29

PHP:制作多维数组的快捷方式

I need to do this:

$array['level1']['level2']['level3'] = 'someval';

However, I don't know how many levels there are going to be. I want to be able to create these arrays with any number of levels automatically. I am trying to adapt the following so that it forms an actual PHP array:

for($i=1;$i<=3;$i++){
  $string .= '_level'.$i;
};
${'array'.$string} = 'someval';

var_dump($array_level1_level2_level3); //Outputs: string(7) "someval"

Obviously that is no replacement for an array. I'm simply looking for a parallel that can be applied to multidimensional arrays. I suspect the answer lies in some kind of recursive function, but I'm not quite sure what.

Update

Here is what I really want to do. I've had trouble sufficiently explaining my problems and as a result the question was closed. So, I tried to take it apart into pieces.

https://stackoverflow.com/questions/8002490/creating-multidimensional-arrays-in-php

  • 写回答

1条回答 默认 最新

  • doutan8506 2011-11-04 05:10
    关注

    You may try the following:

    function makeArray($array, $lowElement, $highElement, $value) {
        if($highElement == $lowElement) {
            $array['level' . $highElement] = $value;
        }
        else {
            $array['level' . $lowElement] = makeArray($array, $lowElement+1, $highElement, $value);
        }
    
        return $array;
    }
    
    $array = array();
    $array = makeArray($array, 1, 5, 'someval');
    print_r($array);   // Output: Array ( [level1] => Array ( [level2] => Array ( [level3] => Array ( [level4] => Array ( [level5] => someval ) ) ) ) )
    

    Output indicates that now you have the following:

    $array['level1']['level2']['level3']['level4']['level5'] = 'someval';

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?