drbz99867 2016-06-02 11:30
浏览 13

将String扩展为多维关联数组

I need to convert people ID's to an associative array. The id's can look like that:

"01"
"01/01"
"01/03/05/05"
etc.

Now I need to put it into an array so I can get to it like this:

$array['01']  
$array['01']['01']  
$array['01']['03']['05']['05']

Any ideas? Thank you in advance!

  • 写回答

1条回答 默认 最新

  • doutu1939 2016-06-02 11:54
    关注

    This is always a bit of a tricky one to work out the first time. The key is to create a reference variable to your resulting array, and move it down through the tree as you parse each step.

    <?php
    $paths = [
        '01',
        '01/01',
        '01/03/05/05',
    ];
    
    $array = []; // Our resulting array
    $_     = null; // We'll use this as our reference
    
    foreach ($paths as $path)
    {
        // Each path begins at the "top" of the array
        $_ =& $array;
    
        // Break each path apart into "steps"
        $steps = explode('/', $path);
    
        while ($step = array_shift($steps))
        {
            // If this portion of the path hasn't been seen before, initialise it
            if (!isset($_[$step])) { $_[$step] = []; }
    
            // Set the pointer to the new level of the path, so that subsequent
            // steps are created underneath
            $_ =& $_[$step];
        }
    }
    

    =

    array (1) [
        '01' => array (2) [
            '01' => array (0)
            '03' => array (1) [
                '05' => array (1) [
                    '05' => array (0)
                ]
            ]
        ]
    ]
    

    You can then test for an element's existence using isset, e.g.

    if (isset($array['01']['03']['05']['05']))
    {
        // do stuff
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大