PHP递归函数将嵌套的{}分隔的字符串转换为数组

时间:2019-06-24 15:48:30

标签: php arrays multidimensional-array nested

我正在尝试在php中构建一个递归函数,该函数采用带有嵌套{}值的字符串并将其转换为嵌套数组。是否有任何可以将其简单拆分的内置函数?

此外,{括号将始终与键位于同一行,即(Main {)而不是Main \ n {。

缩进也将始终保持一致。

下面我要寻找的示例。

  Main{
    NetworkAccess 1; 
    MaxCPE 6; 
    MaxClassifiers 20; 
    GlobalPrivacyEnable 1; 
    BaselinePrivacy{
      AuthTimeout 10; 
      ReAuthTimeout 10; 
      AuthGraceTime 600; 
      OperTimeout 10; 
      ReKeyTimeout 10; 
      TEKGraceTime 600; 
      AuthRejectTimeout 60; 
      SAMapWaitTimeout 1; 
      SAMapMaxRetries 4; 
    }
    UsServiceFlow{
      UsServiceFlowRef 1; 
      QosParamSetType 7; 
      TrafficPriority 2; 
      MaxRateSustained 1000000; 
      SchedulingType 2; 
      MaxTrafficBurst 8000; 
      MaxConcatenatedBurst 8000; 
    }
    DsServiceFlow{
      DsServiceFlowRef 101; 
      QosParamSetType 7; 
      TrafficPriority 2; 
      MaxRateSustained 10000000; 
    }
  }

Array
(
    [Main] => Array
        (
            [NetworkAccess] => 1
            [MaxCPE] => 6
            [MaxClassifiers] => 20
            [GlobalPrivacyEnable] => 1
            [BaselinePrivacy] => Array
                (
                    [AuthTimeout] => 10
                    [ReAuthTimeout] => 10
                    [AuthGraceTime] => 600
                    [OperTimeout] => 10
                    [ReKeyTimeout] => 10
                    [TEKGraceTime] => 600
                    [AuthRejectTimeout] => 60
                    [SAMapWaitTimeout] => 1
                    [SAMapMaxRetries] => 4
                )

            [UsServiceFlow] => Array
                (
                    [UsServiceFlowRef] => 1
                    [QosParamSetType] => 7
                    [TrafficPriority] => 2
                    [MaxRateSustained] => 1000000
                    [SchedulingType] => 2
                    [MaxTrafficBurst] => 8000
                    [MaxConcatenatedBurst] => 8000
                )

            [DsServiceFlow] => Array
                (
                    [DsServiceFlowRef] => 101
                    [QosParamSetType] => 7
                    [TrafficPriority] => 2
                    [MaxRateSustained] => 10000000
                )

        )

)

2 个答案:

答案 0 :(得分:2)

JSON会更好,但由于不希望在不需要逗号的地方使用逗号(PHP不在乎),因此它将变得更加困难。

$string = "[".str_replace(['{', '}', ';'], ['[', '],', ','], $string)."]";
$string =  preg_replace('/([a-z]+)/i', '"$1" =>', $string);
eval("\$result = $string;");
print_r($result);

答案 1 :(得分:0)

当前数据的另一种选择是,使用一致的花括号,可能会使用一个递归函数,该函数利用引用来跟踪当前数据和父数据。

在换行符处展开,并将该数组作为起点。对于每次迭代,请使用array_shift将第一个迭代从顶部移出,如果数组为空,则返回null。

如果最后一个字符是{,则当前字符将是父字符,并设置一个新数组作为下一次迭代的当前字符。

当唯一字符为}时,将父级用于下一个迭代。

例如:

function processItems($items, &$current, &$parent) {
    $item =  trim(array_shift($items));
    if ($item) {

        if (substr($item, -1) === '{') {
            $key = rtrim($item, '{');
            $current[$key] = [];
            processItems($items, $current[$key], $parent);
            return;
        }

        if (trim($item) === '}') {
            processItems($items, $parent, $parent);
            return;
        }

        $parts = explode(' ',  $item);
        $current[$parts[0]] = rtrim($parts[1], ';');

        processItems($items, $current, $parent);
    }
}

$curr = [];
processItems(explode("\n", $data), $curr, $curr);

print_r($curr);

结果

Array
(
    [Main] => Array
        (
            [NetworkAccess] => 1
            [MaxCPE] => 6
            [MaxClassifiers] => 20
            [GlobalPrivacyEnable] => 1
            [BaselinePrivacy] => Array
                (
                    [AuthTimeout] => 10
                    [ReAuthTimeout] => 10
                    [AuthGraceTime] => 600
                    [OperTimeout] => 10
                    [ReKeyTimeout] => 10
                    [TEKGraceTime] => 600
                    [AuthRejectTimeout] => 60
                    [SAMapWaitTimeout] => 1
                    [SAMapMaxRetries] => 4
                )

        )

    [UsServiceFlow] => Array
        (
            [UsServiceFlowRef] => 1
            [QosParamSetType] => 7
            [TrafficPriority] => 2
            [MaxRateSustained] => 1000000
            [SchedulingType] => 2
            [MaxTrafficBurst] => 8000
            [MaxConcatenatedBurst] => 8000
        )

    [DsServiceFlow] => Array
        (
            [DsServiceFlowRef] => 101
            [QosParamSetType] => 7
            [TrafficPriority] => 2
            [MaxRateSustained] => 10000000
        )

)

Php demo