題目:把字符串嵌套關係轉換成數組,字符串只包含成對中括號、數字和逗號
字符串:(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)json
程序:數組
$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]spa