递归重新格式化前缀阵列

时间:2017-02-10 10:07:58

标签: php arrays

如何将平面数组转换为嵌套数组,其中嵌套键的前缀为相同值。例如,说我有以下数组:

[
    'name' => 'a',
    'content' => 'b',
    'author_fullName' => 'c',
    'author_email' => 'd',
    'author_role_name' => 'e'
]

然后阵列的外部是:

[
    'name' => 'a',
    'content' => 'b',
    'author' => [
        'fullName' => 'c',
        'email' => 'd',
        'role' => [
            'name' => 'e'
        ]
    ]
]

理想情况下,我喜欢使用内置数组函数的解决方案,因为我更喜欢函数式语法,而不是使用for循环。我很感激帮助。感谢

2 个答案:

答案 0 :(得分:1)

尝试以下代码:

        string[] code = new string[9];
        int[] intCode = new int[9];
        int cd = 0, dvd = 0, video = 0, book = 0;
        for (int i = 0; i < 10; i++)
        {
            bool isCorrectInput = false;
            while (!isCorrectInput)
            {
                isCorrectInput = true;
                Console.Write("Enter code#{0}: ", i+1);
                code[i] = Console.ReadLine();
                if (code[i].Length == 1)
                {
                    intCode[i] = Convert.ToInt32(code[i]);
                    // intCode  /= 100000;
                    switch (intCode[i])
                    {
                        case 1:
                            cd++;
                            break;
                        case 2:
                            dvd++;
                            break;
                        case 3:
                            video++;
                            break;
                        case 4:
                            book++;
                            break;
                        default:
                            isCorrectInput = false;
                            break;
                    }
                }
                else
                    isCorrectInput = false;
                if (!isCorrectInput)
                    Console.WriteLine("INVALID CODE ENTERED!");
            }
        }

答案 1 :(得分:0)

另一种解决方案

$delimiter = '_';
$result = [];
foreach($array as $k => $v)
{
    $split = explode($delimiter, $k, 2);//explode only as much as we need
    if(count($split) > 1)
    {
        if(!isset($result[$split[0]]))
        {
            $result[$split[0]] = [];
        }
        //this assumes we're not interested in more than two depths
        //in tandem with the explode limit
        $result[$split[0]][$split[1]] = $v;
    }
    else
    {
        $result[$k] = $v;
    }
}