1
I’m using the following query in GraphQL:
$q = "
{
shop {
name
}
}
";
But I want to do it dynamically in PHP in the following way:
$fieldName = 'name';
$query = [
"shop" => [
$fieldName
]
];
And later on when passing the query to GraphQL I wanna convert in GraphQL suitable format.
Well I can do it by using iterative function in PHP but that doesn’t seem very efficient.
function formatGraphQLQuery($queryArray, $indentation = 0) {
$formattedQuery = '';
$indent = str_repeat(' ', $indentation);
foreach ($queryArray as $field => $value) {
if (is_array($value)) {
$formattedQuery .= $indent . $field . " {n";
$formattedQuery .= formatGraphQLQuery($value, $indentation + 1);
$formattedQuery .= $indent . "}n";
} else {
$formattedQuery .= $indent . $value . "n";
}
}
return $formattedQuery;
}
Also using json_encode doesn’t work as it returns in the following format:
{
"shop":[
"name"
]
}
So what would be an idea solution?
0