update page now

Voting

: max(three, six)?
(Example: nine)

The Note You're Voting On

Alexey Loktionov (error at pochta dot ru)
15 years ago
Here is much powerful pg_parse_array() variant, based on FSM: for any dimension Postgres arrays (its string representation must be well-formed), with quotation rules checks, complexity O(N), where N is a length of string representation of Postgres array:

<?php

define('STATE_BEGIN', 1);
define('STATE_INARRAY',2);
define('STATE_OUTARRAY', 3);
define('STATE_INSLASH', 4);
define('STATE_INQUOTES', 5);

function pg_parse_array($value) {
        $resultArray = $indexArray = array(); $level = $index = 0;
        $ptr = &$resultArray;
        for($i = 0; $i < strlen($value); $i++){
            switch($level){
                case 1:
                    if($index > 0){
                        $ptr = & $ptr[sizeof($ptr)];
                    }
                    $indexArray[++$index] = & $ptr;
                    break;
                case -1:
                    $ptr = & $indexArray[--$index];
                    break;
            }
            $level = processFSM($value{$i}, $ptr);
        }
        return $resultArray;
    }
    
    function processFSM($chr, &$result){
        static $state = STATE_BEGIN, $index = 0;
        $level = 0;
        switch(true){
            case $chr == '{' && in_array($state, array(STATE_BEGIN,STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_INARRAY;
                $index = 0;
                $level = +1;
                break;
            case $chr == '}' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_OUTARRAY;
                $level = -1;
                break;
            case $chr == '\\' && $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : STATE_INSLASH;
                break;
            
            case $chr == '"' && !in_array($state, array(STATE_BEGIN,STATE_INSLASH), true):
                $state = $state === STATE_INQUOTES ? STATE_INARRAY : STATE_INQUOTES;
                break;
            
            case $chr == ',' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $index = sizeof($result);
                break;
            
            case $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : $state;
                isset($result[$index]) or $result[$index] = '';
                $result[$index] .= $chr;
                break;
        }
        return $level;
    }

?>

<< Back to user notes page

To Top