With PHP parsing JSON-array-string

Title: converts a string array into nesting relationship, a string contains only the pair of brackets, comma and number
strings: (1, (1,2, (1, (1,2, (1)), 3) ), 3, (1, (2, ((1 ((1, (1,2, (2,3), 4,5), 3), 2)), 2)), (( 2,3), 2,3), 4,5) 5)

program:

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

Output Results: [1, [1, [1, [1, [1]], 3]] 3, [1, [1, [[1, [[1, [1 , [2,3], 4,5], 3], 2]], 2]], [[1,2,3], 2,3], 4,5], 5]

 

Reproduced in: https: //www.cnblogs.com/caly/p/5786472.html

Guess you like

Origin blog.csdn.net/weixin_34008805/article/details/93538136