Skip to content

Instantly share code, notes, and snippets.

@3amprogrammer
Last active July 22, 2018 14:17
Show Gist options
  • Save 3amprogrammer/fefcb4134f5e9340ca7b6f28b0e4dcbf to your computer and use it in GitHub Desktop.
Save 3amprogrammer/fefcb4134f5e9340ca7b6f28b0e4dcbf to your computer and use it in GitHub Desktop.
<?php
/**
* Aggregates values as a JSON array
* @param array $columns
* @return string
*/
function json_object(array $columns): string
{
reset($columns);
$alias = key($columns);
$column = array_shift($columns);
$json = sprintf("CONCAT('{','\"%s\":\"',%s,", $alias, $column);
foreach ($columns as $alias => $column) {
$json .= sprintf("'\",\"%s\":\"',%s,", $alias, $column);
}
$json .= "'\"}')";
return $json;
}
/**
* Aggregates name/value pairs as a JSON object
* @param array $columns
* @param bool $distinct
* @return string
*/
function json_object_agg(array $columns, bool $distinct = true): string
{
return json_array(json_object($columns), $distinct);
}
/**
* Aggregates values as a JSON array
* @param string $column
* @param bool $distinct
* @return string
*/
function json_agg(string $column, bool $distinct = true): string
{
return json_array("CONCAT('\"', $column, '\"')", $distinct);
}
/**
* This is an internal function. Use json_agg/json_object_agg instead.
* @param string $expr
* @param bool $distinct
* @return string
*/
function json_array(string $expr, bool $distinct = true): string
{
return sprintf("CONCAT('[', COALESCE(GROUP_CONCAT(%s %s), ''), ']')", $distinct ? "DISTINCT" : "", $expr);
}
$pdo = ...
$query = 'select
q.text,
%s as answers
FROM questions q
INNER JOIN answers a ON a.question_id = q.question_id
group by q.question_id';
$stmt = $pdo->prepare(sprintf($query, json_object_agg([
"text" => "a.text",
"id_correct" => "a.is_correct"
]));
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment