【问题标题】:Convert an array of strings, each string has dot separated values, to a multidimensional array将字符串数组(每个字符串都有点分隔值)转换为多维数组
【发布时间】:2013-02-28 10:05:53
【问题描述】:

我有以下数组:

Array
(
    [0] => INBOX.Trash
    [1] => INBOX.Sent
    [2] => INBOX.Drafts
    [3] => INBOX.Test.sub folder
    [4] => INBOX.Test.sub folder.test 2
)

如何将这个数组转换成这样的多维数组:

Array
(
    [Inbox] => Array
        (
            [Trash] => Array
                (
                )

            [Sent] => Array
                (
                )

            [Drafts] => Array
                (
                )

            [Test] => Array
                (
                    [sub folder] => Array
                        (
                            [test 2] => Array
                                (
                                )

                        )

                )

        )

)

【问题讨论】:

标签: php arrays multidimensional-array


【解决方案1】:

试试这个。

<?php
$test = Array
(
    0 => 'INBOX.Trash',
    1 => 'INBOX.Sent',
    2 => 'INBOX.Drafts',
    3 => 'INBOX.Test.sub folder',
    4 => 'INBOX.Test.sub folder.test 2',
);

$output = array();
foreach($test as $element){
    assignArrayByPath($output, $element);   
}
//print_r($output);
debug($output);
function assignArrayByPath(&$arr, $path) {
    $keys = explode('.', $path);

    while ($key = array_shift($keys)) {
        $arr = &$arr[$key];
    }
}

function debug($arr){
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}

【讨论】:

    【解决方案2】:

    我对此非常感兴趣,因为尝试这样做时遇到了巨大的困难。在查看(并通过)乔恩的解决方案后,我想出了这个:

    $array = array();
    function parse_folder(&$array, $folder)
    {
        // split the folder name by . into an array
        $path = explode('.', $folder);
    
        // set the pointer to the root of the array
        $root = &$array;
    
        // loop through the path parts until all parts have been removed (via array_shift below)
        while (count($path) > 1) {
            // extract and remove the first part of the path
            $branch = array_shift($path);
            // if the current path hasn't been created yet..
            if (!isset($root[$branch])) {
                // create it
                $root[$branch] = array();
            }
            // set the root to the current part of the path so we can append the next part directly
            $root = &$root[$branch];
        }
        // set the value of the path to an empty array as per OP request
        $root[$path[0]] = array();
    }
    
    foreach ($folders as $folder) {
        // loop through each folder and send it to the parse_folder() function
        parse_folder($array, $folder);
    }
    
    print_r($array);
    

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2016-02-09
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      相关资源
      最近更新 更多