It's possible, but it's weird
What you are trying to do is a JSON object with repeated keys / properties. This is unusual because many JSON libraries will fail to read a JSON with repeated keys, and even if it does not give an error, they will probably not allow you to read all the data. Using your example of wanting a result:
{"name": "student", "name": "barbara_cristina", "name": "carolina_deus"}
When doing:
$obj = json_decode( $json );
echo $obj->nome;
You expect me to print what? aluno
, barbara_cristina
or carolina_deus
?
Unable to do with json_encode()
Because json_encode()
does not produce objects with repeated keys. You have to make gambi in your hand. Something like this:
<?php
$result = array( "2" => "aluno" , "8" => "barbara_cristina" , "13" => "carolina_deus" );
$fakeItens = array();
foreach ( $result as $item )
$fakeItens[] = '"nome":' . json_encode( $item );
$fakeJson = "{" . implode( ',' , $fakeItens ) . "}";
echo $fakeJson;
This code will generate correct JSON, even if the item has quotes or special characters.
Instead of putting a fixed header, remove the keys?
It looks like the numeric keys that are bothering you. If the "header" is a fixed thing, how do you not put it, but take the numbers?
<?php
$result = array( "2" => "aluno" , "8" => "barbara_cristina" , "13" => "carolina_deus" );
echo json_encode( array_values( $result ) );
Compare the result of the two codes:
{"nome":"aluno","nome":"barbara_cristina","nome":"carolina_deus"}
["aluno","barbara_cristina","carolina_deus"]