Reputation: 127
I want to get this as a single object because I work with a JObject on the frontend.
I got an array at the moment but I am unsure how i should modify it so it returns a single object instead.
This is the code:
$contacts = array();
while ($row = mysqli_fetch_array($stmt))
{
$contact = array("ID" => $row['ProduktID'],
"Name" => $row['ProduktNamn'],
"Number" => $row['ProduktPris']);
array_push($contacts, $contact);
}
echo json_encode($contacts, JSON_PRETTY_PRINT);
And the goal is for it to look something like this with "results" as well so I can reach the whole thing:
Upvotes: 0
Views: 62
Reputation: 7911
Like this? Keep in mind an object is different then an array and your question is rather confusing.
while ($row = mysqli_fetch_array($stmt)){
$contact[] = [
"ID" => $row['ProduktID'],
"Name" => $row['ProduktNamn'],
"Number" => $row['ProduktPris']
];
}
json_encode(['result' => $contact]); // Forget the JSON_PRETTY_PRINT.
Using this method []
, it will use the first available numeric index starting with 0. This way you don't have to push an array.
Upvotes: 0
Reputation: 3536
To wrap your array of contacts in an object with a single results
property:
echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
Upvotes: 2
Reputation: 301
You can use typecasting to convert an array to an object:
$object = (object) $array_name;
or manually convert it into an object
$object = object;
foreach($arr as $key => $value)
{
$object->$key = $value;
}
Upvotes: 2