1

我需要一个将查询字符串解析为多维数组的函数。查询字符串可能看起来像这样:

?fields=incidents:(id,shortdescription,action,request);people:(unid,name)&format=json

返回的数组应该是这样的:

array(
   'fields' => array(
      'incidents' => array(
         'id',
         'shortdescription',
         'action',
         'request'
      ),
      'people' => array(
         'unid',
         'name'
      ),
   ),
   'format' => 'json'
);

我希望分隔符是动态的,因此它们将驻留在这样的数组中:

$separators = array(';', ':', ',');

此数组中分隔符的顺序将决定查询字符串的解析顺序。

有人有这样的方便吗???

问候,

标记

4

2 回答 2

0

我自己,我想出了这个:

protected static function split( $value, $sep = ',' )
{   
    if ( str_contains( $value, $sep ) ) 
        $value = explode( $sep, $value );

    return $value;
} 

protected static function multi_split( $value )
    {
        $arr = array();

        // Do we have multiple models?
        $parts = static::split( $value, '+' );        
        if ( count( $parts ) > 1 ) {
            foreach( $parts as $part ) {
                $models = static::split( $part, ':' ); 
                if ( count( $models ) > 1 ) {
                    $fields = static::split( trim($models[1], '()'), ',' );                   
                    $arr[$models[0]] = $fields;   
                }   
            }             

            return $arr;  
        } 

        // Do we have a single model?
        $parts = static::split( $value, ':' ); 
        if ( count( $parts ) > 1 ) {
            $fields = static::split( trim($parts[1], '()'), ',' );               
            $arr[$parts[0]] = $fields;

            return $arr;  
        } 

        // Do we have a comma-separated param?
        $parts = static::split( $value, ',' );
        if ( count( $parts ) > 1 ) 
            return $parts; 

        // Do we have a string param?
        return $value;

    }

我想摆脱很多重复。而且,它还不是很动态!

于 2012-09-22T14:54:04.120 回答
0

为了让你开始:

$final = array();
$keys = explode("&", $_SERVER['QUERY_STRING']);
foreach ($keys as $key => $value) {

    $final[$key] = $value;

    $child = explode(";", $value);
    foreach ($child as $key2 => $value2) {
        $final[$key][$key2] = array();

        $subchild = explode(":", $value2);
        foreach ($subchild as $key3 => $value3) {
            $subsubchild = explode(",", $value3);
            $final[$key][$key2][$key3] = $subsubchild;
        }
    }
}

我没有对此进行测试,但希望能知道我要去哪里......

这可以更新以创建一个接受分隔符的函数以使其真正递归,这样您就可以调用该函数,而不是在循环内的循环内有一个循环......

于 2012-09-22T13:32:35.467 回答