In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.
If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.
$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
// Force the outer structure into an object rather than array
echo json_encode($arrytest , JSON_FORCE_OBJECT);
// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}
Answer from Michael Berkowski on Stack OverflowIn JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.
If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.
$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
// Force the outer structure into an object rather than array
echo json_encode($arrytest , JSON_FORCE_OBJECT);
// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}
Arrays with continuous numerical keys are encoded as JSON arrays. That's just how it is. Why? Because it makes sense.
Since the keys can be expressed implicitly through the array encoding, there is no reason to explicitly encoded them as object keys.
See all the examples in the json_encode documentation.
Here is my PHP and Jquery: https://pastebin.com/ZCay6A55
Issue is that my Jquery is expecting a JSON result from PHP. In the PHP, I have created a nested array, which is then used by json_encode(). Issue is that when the result is alerted, I get no result.
If I modify Jquery such that I comment out dataType:"JSON", I am able to get a successful alert with the correct data (though I am not sure the format is correct).
So my PHP is attempting to create a JSON array of a nested array, but if Jquery is set to expect a JSON array, it doesn't seem to find the result. If jquery is not set to expect a JSON array, it finds the result. I think it's my PHP that's somehow not encoding my nested array into JSON properly.
A JSON array has no explicit indexes, it's just an ordered list. The only JSON data structure that has named keys is an object. The literal should make this quite obvious:
["foo", "bar", "baz"]
This array has no named indices and there isn't any provision to add any.
PHP conflates both lists and key-value stores into one array data type. JSON doesn't.
This is your object:
$parent=new StdClass();
$parent->ID=101;
$parent->ParentID=0;
$parent->Name='Root One';
$child1=new StdClass();
$child1->ID=1011;
$child1->ParentID=$parent->ID;
$child1->Name='Child One';
$parent->Children[]=$child1;
$child1_1=new StdClass();
$child1_1->ID=10111;
$child1_1->ParentID=$child1->ID;
$child1_1->Name='Child One One';
$child1->Children[]=$child1_1;
This is your JSON convert function:
echo json_encode($parent,JSON_PRETTY_PRINT);
and this is your object coded into JSON format:
{
"ID": 101,
"ParentID": 0,
"Name": "Root One",
"Children": [
{
"ID": 1011,
"ParentID": 101,
"Name": "Child One",
"Children": [
{
"ID": 10111,
"ParentID": 1011,
"Name": "Child One One"
}
]
}
]
}
The answer came later because I started learning PHP later. Anyway, some day, someone might find it useful.
Try something like this:
//initialize array
$myArray = array();
//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);
//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;
//convert to json
$json = json_encode($myArray);
Here is a shorter way:
$myArray = array();
$myArray[] = array("id" => 1, "data" => 45);
$myArray[] = array("id" => 3, "data" => 54);
//convert to json
$json = json_encode($myArray);
Apologies before I begin. Anything remotely database orientated/PHP/JSON is entirely new to me and so I am trying to muddle through to connect my app (written in swift) to a database.
I have a data base called "mojitoDatabase". Inside of said database there is currently one table called "Menu". I've written a .php file to retrieve the information from all of the rows inside the table and it currently returns:
[{
"id": "1",
"name": "Spaghetti and Meatballs"
}, {
"id": "2",
"name": "Margherita Pizza"
}, {
"id": "3",
"name": "Grilled Steelhead Trout"
}](I've taken out some of the columns to save on space for this post so lets pretend there's only two fields ("id" and "name"). What I'm trying to achieve is the following formatted output with the table name at the top level of the returned array:
{
"Meals": 1 [{
"id": "1",
"name": "Spaghetti and Meatballs"
}, {
"id": "2",
"name": "Margherita Pizza"
}, {
"id": "3",
"name": "Grilled Steelhead Trout"
}],
"Drinks": 2 [{
"id": "1",
"name": "Lemonade"
}, {
"id": "2",
"name: "Orange Juice"
} {
"id": "3",
"name": "Coffee"
}The drinks array is there just for example sake. It would also be handy if the tables could be indexed but I'm not sure if that's possible? I'm used to indices starting at 0 but I have a hunch that indices start from one in MySQL? Sorry if this is way too basic/completely wrong!
Current code in .php file:
$sql = "SELECT * FROM Menu";
if ($result = mysqli_query($con, $sql)) {
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}Thanks to anyone who's taken the time to read.
Try this code
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
$i=0;
while ($row = $stmt->fetch_assoc()) {
$users[$i]['id'] = $row['id'];
$users[$i]['last_active'] = $row['last_active'];
$i++;
}
echo json_encode($users);
You can use temporary array like this:
$users = array();
$stmt = $mysqli->query('SELECT id, last_active FROM users WHERE status = 1');
while ($row = $stmt->fetch_assoc()) {
$tempArray = []; // added
$tempArray[] = $row['id'];
$tempArray[] = $row['last_active'];
$users[] = $tempArray; // added
}
echo json_encode($users);
or directly assign both values :
$users[] = array($row['id'],$row['last_active']);
Sure, you could send an array of array. PHP associative array will become a javascript object.
In PHP:
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
echo json_encode($data);
and then on jQuery
var data = jQuery.parseJSON(response);
then you could then do something like this to access the values
console.log(data.fruits[0]); // apple
console.log(data.animals[1]); // elephant
The code should be like the following:
$columns = array(/*Data*/);
$columns1 = array(/*Data1*/);
echo json_encode(array($columns,$columns1));
in jQuery use
var columns_array=jQuery.parseJSON(response);
columns=columns_array[0];
columns1=columns_array[1];