如何通过使下一个项目成为前一个子项目的一部分来移动数组?

How to shift array by making next item the part of subitem of previous one?

数组:

$array = [
  'A',
  'B',
  'C'
  //and so on
]

预期结果:

$array = [
    [
        'value' => 'A',
        'names'    => [
            '1' => 'A',
            '2' => 'A'
        ],
        'child' => [
            'value' => 'B',
            'names'    => [
                '1' => 'B',
                '2' => 'B'
            ],
            'child' => [
                'value' => 'C',
                'names'    => [
                    '1' => 'C',
                    '2' => 'C'
                ],
                'child' => [
                    // and so on...
                ]
            ]
        ]
    ]
];

我研究了一个函数array_merge_recursive。 但是这个函数不会移动数组。

需要实现:简单数组交错数组

我不明白你想要什么 names,但是这段代码正在生成你想要的数组:

$array = [
    'A',
    'B',
    'C'
    //and so on
];
$result = [];
for($i = count($array) - 1 ; $i >= 0 ; $i--){
    $result = [
        'value' => $array[$i],
        'names'    => [
            '1' => $array[$i],
            '2' => $array[$i],
        ],
        'child' => $result
    ];
}

输出:

Array
(
    [value] => A
    [names] => Array
        (
            [1] => A
            [2] => A
        )

    [child] => Array
        (
            [value] => B
            [names] => Array
                (
                    [1] => B
                    [2] => B
                )

            [child] => Array
                (
                    [value] => C
                    [names] => Array
                        (
                            [1] => C
                            [2] => C
                        )

                    [child] => Array
                        (
                        )

                )

        )

)