Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Give a name to an array of JSON objects?

Tags:

json

php

I have managed to get data from database in PHP file. From there(data.php),

$output = json_encode($result);

The result would be like this,

$output=[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]

So how do I give name "kitten" an array of kitty objects in php format?

For example like

"kitten":[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
like image 476
user1739825 Avatar asked Aug 22 '13 10:08

user1739825


People also ask

How do you name an array in JSON?

Array Datatype in JSON Similar to other programming languages, a JSON Array is a list of items surrounded in square brackets ([]). Each item in the array is separated by a comma. The array index begins with 0. The square brackets [...] are used to declare JSON array.

Can you have an array of JSON objects?

Yes, you can create an array of objects. Technically, a 2D array is valid JSON.

What is json_encode and json_decode in PHP?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What is JSON array in PHP?

A JSON array is produced by assigning a contiguous integer-indexed PHP array into a JSON domain tree path. A PHP array variable is contiguous integer-indexed if it contains only integer keys that are sequenced from 0 to n -1 (where n is the total number of items in the array).


1 Answers

You have to wrap your result in another array on the 'kitten' key :

$output = json_encode(['kitten' => $result]);
like image 196
Brewal Avatar answered Sep 21 '22 00:09

Brewal