Php 将十进制数/MIB样式的字符串转换为数组索引

Php 将十进制数/MIB样式的字符串转换为数组索引,php,string,multidimensional-array,Php,String,Multidimensional Array,我正在尝试将mib样式的字符串转换为PHP数组索引。诀窍是我必须对数量可变的字符串执行此操作。例如: $strings = ['1.1.1' => 1, '1.1.2' => 2, '1.2.1' => 1]; # Given the above, generate the below: $array = [ 1 => [ 1 => [1 => 1, 2 => 2] ], 2 => [1 => 1] ] ] ] ] 我想不出一种方法,它不仅

我正在尝试将mib样式的字符串转换为PHP数组索引。诀窍是我必须对数量可变的字符串执行此操作。例如:

$strings = ['1.1.1' => 1, '1.1.2' => 2, '1.2.1' => 1];
# Given the above, generate the below:
$array = [ 1 => [ 1 => [1 => 1, 2 => 2] ], 2 => [1 => 1] ] ] ] ]

我想不出一种方法,它不仅仅是一种野蛮、低效的方法。欢迎提供任何有用的函数/方法/建议。

您可以采用递归方法,因为您提供的问题/结果似乎具有递归性质。(当然,应用与递归函数相同的逻辑,可以通过循环获得相同的结果)

因此,在假设不存在冲突字符串输入/边缘情况的情况下,以下可能是一种方法:

循环所有字符串及其值,将其分解并通过引用传递结果数组来创建嵌套结构

function createNested($pieces, $currentIndex, &$previous, $value)
{
    $index = $pieces[$currentIndex];
    // Our base case: when we reached the final/deepest level of nesting.
    // Hence when the we reached the final index.
    if ($currentIndex == count($pieces) - 1) {
        // Can now safely assign the value to index.
        $previous[$index] = $value;
    } else {
        // Have to make sure we do not override the key/index.
        if (!key_exists($index, $previous)) {
            $previous[$index] = [];
        }

        // If the key already existed we can just make a new recursive call (note one level deeper as we pass the array that $previous[$index] points to.
        createNested($pieces, $currentIndex + 1, $previous[$index], $value);
    }
}

$strings = ['1.1.1' => 1, '1.1.2' => 2, '1.2.1' => 1];

$result = [];
foreach ($strings as $string => $value) {
    // Break up the string by .
    createNested(explode('.', $string), 0, $result, $value);
}

echo '<pre>';
print_r($result);
echo '</pre>';

我意识到我问的问题并不完全是我需要问的(抱歉!),但这确实回答了我的问题,我认为根据我的需要进行修改很容易。我真的很感谢你的帮助!
Array
(
    [1] => Array
    (
        [1] => Array
        (
            [1] => 1
            [2] => 2
        )
        [2] => Array
        (
            [1] => 1
        )
    )
)