php - 将十进制数/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] ] ] ] ]
我想不出一种方法来做到这一点,而不仅仅是一种蛮力、低效的方法。欢迎任何有用的功能/方法/建议。
解决方案
您可以采用递归方法,因为您提供的问题/结果似乎具有递归性质。(您可以通过循环实现相同的结果,应用与递归函数相同的逻辑当然)
因此,假设没有任何冲突的字符串输入/边缘情况,以下可能是一种方法:
循环遍历所有字符串及其值,将其分解并通过其引用传递结果数组来创建嵌套结构。
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
)
)
)
推荐阅读
- node.js - 超级账本结构通道创建节点 SDK - 错误
- mongodb - 有什么方法可以在 mongoDB 中使用 $exists 和 $expr 吗?
- android - 如何在 Android Studio 中自动生成飞镖函数的标头注释?
- python - 修改同一类的另一个实例时实例变量更改值,Python-Tkinter
- sql - ORACLE SQL - 将两个查询和一个值相加
- javascript - 使用 d3js 污染图表
- android - Flutter - 无法更新或删除应用内购买的托管产品?
- css - 为 prod 样式构建 angular 8 应用程序后为空
- python - 按属性(点)与括号访问熊猫列值时出现奇怪的错误
- tensorflow - 尝试导入 tensorflow 时,我得到了“超出顶级包的导入”