将String扩展为多维关联数组

时间:2016-06-02 11:30:38

标签: php arrays multidimensional-array

我需要将人ID转换为关联数组。 id可以是这样的:

  

“01”
  “01/01”
  “01/03/05/05”
  等

现在我需要把它放到一个数组中,所以我可以这样做:

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

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

第一次锻炼总是有点棘手。关键是为结果数组创建一个引用变量,并在解析每一步时将其向下移动到树中。

<?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)
            ]
        ]
    ]
]

然后,您可以使用isset测试元素的存在,例如

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