zoukankan      html  css  js  c++  java
  • 用PHP解析类JSON字符串为数组的实现

    题目:把字符串嵌套关系转换成数组,字符串只包含成对中括号、数字和逗号
    字符串:(1,(1,2,(1,(1,2,(1)),3)),3,(1,(1,2,((1((1,(1,2,(1,2,3),4,5),3),2)),2)),((1,2,3),2,3),4,5),5)

    程序:

    $string = '(1,(1,2,(1,(1,2,(1)),3)),3,(1,(1,2,((1,((1,(1,2,(1,2,3),4,5),3),2)),2)),((1,2,3),2,3),4,5),5)';
    
    $result = $previous = [];
    $current = $number = null;
    
    $i = 0;
    while ( isset($string[$i]) ) {
        $value = $string[$i];
    
        switch ($value) {
            case '(':
                if ( is_null($current) ) {
                    $current = &$result;
                } else {
                    $previous[] = &$current;
                    $current[] = [];
                    $current = &$current[count($current) - 1];
                }
                break;
            case ')':
                if ( !is_null($number) ) {
                    $current[] = intval($number);
                    $number = null;
                }
    
                $last = count($previous) - 1;
                $current = &$previous[$last];
                array_pop($previous);
                break;
            case ',':
                if ( !is_null($number) ) {
                    $current[] = intval($number);
                    $number = null;
                }
                break;
            default:
                $number .= $value;
                break;
        }
    
        $i++;
    }
    
    echo json_encode($result);

    输出结果:[1,[1,2,[1,[1,2,[1]],3]],3,[1,[1,2,[[1,[[1,[1,2,[1,2,3],4,5],3],2]],2]],[[1,2,3],2,3],4,5],5]

  • 相关阅读:
    [SDOI2011]消防
    10.15 上午 考试
    松鼠搬家 ( 切比雪夫距离 到 曼哈顿距离 )
    10.14 上午 考试
    10.13 下午
    bzoj2640 元素 线性基+贪心
    猪国杀 大模拟
    10.13 上午 考试
    10.12 两次考试
    阿狸和桃子的游戏
  • 原文地址:https://www.cnblogs.com/caly/p/5786472.html
Copyright © 2011-2022 走看看