PHP: Build an Array of Response Data

 Help Us Improve Our API Documentation!

We're beginning an initiative to improve our API docs. We would love your help!

Please take this quick 4-question survey to help us out! Thank you in advance for your time!

Some users have requested example scripts to parse the basic survey response array into something more malleable for working with the data. The following example is very similar to code we use to organize survey data into an array that is easier to work with, at least within PHP.

/**
*  splitFieldName - Splits a returned field name (the merge codes) and splits it up into an array via regex
*  @param string $fieldname Field to split
*  @return mixxed array with result or error
* */
public static function splitFieldNames($fieldname)
{
//Added error protection (if it's an array we'll assume its in field_return format)
if(is_array($fieldname))
return $fieldname;
if(!is_string($fieldname))
return false;
$fieldname = stripslashes($fieldname);
// Use regex to pull out the field names - Identical to Query, can be replaced if Query's gets changed
$pattern = '/\\[(question|url|variable|calc|comment)\\(("(?:\\\\"|[^"])+"|\d+)\\)';
$pattern .= '(?:\\s?,\\s?option\\(("(?:\\\\"|[^"]){0,}"|\d{0,})\\))?';
$pattern .= '(?:\\s?,\\s?question_pipe\\(' . '("' . '(?:\\\\"|[^"])' . '{0,}"|\d{0,})' . '\\))?';
$pattern .= '(?:\\s?,\\s?page_pipe\\(("(?:\\\\"|[^"]){0,}"|\d{0,})\\))?';
$pattern .= '(?:\\s?,\\s?(select))?';
$pattern .= '(?:\\s?,\\s?(concat))?';
$pattern .= '(?:\\s?,\\s?(any))?';
$pattern .= '(?:\\s?,\\s?(all))?';
$pattern .= '(?:\\s?,\\s?(delimit))?';
$pattern .= '(?:\\s?,\\s?(lines))?';
$pattern .= '\\]/';
$match_count = preg_match_all($pattern, $fieldname, $matches);
if ($match_count == 0)
return false;
$type = addslashes(stripslashes($matches[1][0]));
$variable = is_numeric($matches[2][0]) ? intval($matches[2][0]) : stripslashes(substr($matches[2][0], 1, -1));
$option = is_numeric($matches[3][0]) ? intval($matches[3][0]) : stripslashes(substr($matches[3][0], 1, -1));
$question_pipe = is_numeric($matches[4][0]) ? intval($matches[4][0]) : stripslashes(substr($matches[4][0], 1, -1));
$page_pipe = is_numeric($matches[5][0]) ? intval($matches[5][0]) : stripslashes(substr($matches[5][0], 1, -1));
$select = $matches[6][0] == "select" ? true : false;
$concat = $matches[7][0] == "concat" ? true : false;
$any = $matches[8][0] == "any" ? true : false;
$all = $matches[9][0] == "all" ? true : false;
$delimit = $matches[10][0] == "delimit" ? true : false;
$lines = $matches[11][0] == "lines" ? true : false;
// build the array for return
$field_return = array(
"type" => $type,
"id" => $variable,
"optionid" => $option,
"question_pipe" => $question_pipe,
"page_pipe" => $page_pipe,
"select" => $select,
"concat" => $concat,
"any" => $any,
"all" => $all,
"delimit" => $delimit,
"lines" => $lines
);
return $field_return;
}