首页 > 解决方案 > 将十进制数/MIB 样式字符串转换为数组索引

问题描述

我正在尝试将 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] ] ] ] ]

我想不出一种方法来做到这一点,而不仅仅是一种蛮力、低效的方法。欢迎任何有用的功能/方法/建议。

标签: phpstringmultidimensional-array

解决方案


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

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

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

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

推荐阅读