Skip to content

Instantly share code, notes, and snippets.

@andris9
Last active December 23, 2015 23:49
Show Gist options
  • Save andris9/6712550 to your computer and use it in GitHub Desktop.
Save andris9/6712550 to your computer and use it in GitHub Desktop.
Parses query string
<?php
$str = "/v1/combinedObjects:(id,user_id,value,title,person:(id,name,activities_count,owner_id:(name),activities_count),organization:(id,name))";
print_r(queryParser($str));
function queryParser($query){
// split tokens
$tokens = preg_split('/,|(?=:\\(|\\))|(?<=:\\(|\\))/', $query, -1, PREG_SPLIT_NO_EMPTY);
array_shift($tokens);
// current level elements
$node = array();
// parents for recursion
$path = array();
// placeholder for closed node
$last = false;
// current key name
$key = false;
foreach($tokens as $i => $token){
switch($token){
// go one level deeper, save current level to $path and open a new one
case ":(":
$path[] = array($key, $node);
$node = array();
break;
// close current level, go up one step and store current list to parent level
case ")":
$last = $node;
list($key, $node) = array_pop($path);
if(!count($node) && !$key){
$node = $last;
}else{
$node[] = array("key" => $key, "fields" => $last);
}
break;
// if next element is :( then this is a key, otherwise append to current level
default:
if($tokens[$i + 1] == ":("){
$key = $token;
}else{
$node[] = $token;
}
break;
}
}
return $node;
}
Array
(
[0] => id
[1] => user_id
[2] => value
[3] => title
[4] => Array
(
[key] => person
[fields] => Array
(
[0] => id
[1] => name
[2] => activities_count
[3] => Array
(
[key] => owner_id
[fields] => Array
(
[0] => name
)
)
[4] => activities_count
)
)
[5] => Array
(
[key] => organization
[fields] => Array
(
[0] => id
[1] => name
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment