Question:
My JSON currently returns this code below:
{"2":"aluno","8":"barbara_cristina","13":"carolina_deus"}
Is there any way I can add a "header" in the places of numbers 2, 8 and 13? I wanted it to be like this:
{"nome":"aluno","nome":"barbara_cristina","nome":"carolina_deus"}
These are the commands I use to generate the JSON.
$aluno = array();
while($row = mysqli_fetch_array($verifica))
{
$aluno[]= $row['username'];
}
$alunoToledo = array();
while($lista2 = mysqli_fetch_array($verifica2))
{
$alunoToledo[] = $lista2['username'];
}
$result = array_diff($aluno,$alunoToledo);
json_encode($result)
Can anyone help me if this is possible?
Answer:
To do this, just add the keys:
$aluno = array();
while($row = mysqli_fetch_array($verifica))
{
$aluno[]= $row['username'];
}
$alunoToledo = array();
while($lista2 = mysqli_fetch_array($verifica2))
{
$alunoToledo[] = $lista2['username'];
}
$results = array_diff($aluno,$alunoToledo);
echo '{nome:' . $results[0] . ',nome:' . $results[1] . ',nome:' . $results[2] . '}';
However, the use of JSON is not valid this way, because when using JSON, you must have a key for each one, it would be something similar to this:
[{nome: "nome1"},{nome: "nome2"},{nome: "nome3"},{nome: "nome4"}]
And so, you should do it like this:
$collection = array();
foreach ($results as $result){
$collection[]['nome'] = $result;
}
echo json_encode($collection);