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 Overflow
🌐
W3Docs
w3docs.com › php
JSON_ENCODE of multidimensional array giving different results
<?php $data = [ "name" => "John Doe", "address" => [ "street" => "123 Main St", "city" => "Anytown", "state" => "CA", "zip" => "12345", ], "phone numbers" => [ "home" => "555-555-5555", "work" => "555-555-5556", ], ]; $json = json_encode($data); echo $json; ... After executing the code, you can see the sub-arrays "address" and "phone numbers" have been converted into JSON objects.
🌐
Alvin Alexander
alvinalexander.com › php › php-json_encode-convert-array-to-json-example
A PHP json_encode array conversion example | alvinalexander.com
<?php header('Content-type: text/html'); echo json_encode( array( array('symbol' => 'AAPL', 'price' => '525.00'), array('symbol' => 'GOOG', 'price' => '600.00'), array('symbol' => 'TSLA', 'price' => '220.00') ) ); ?>
🌐
PHP
php.net › manual › en › function.json-encode.php
PHP: json_encode - Manual
If the parameter is an array or object, it will be serialized recursively. If a value to be serialized is an object, then by default only publicly visible properties will be included. Alternatively, a class may implement JsonSerializable to control how its values are serialized to JSON. The encoding is affected by the supplied flags and additionally the encoding of float values depends on the value of serialize_precision.
🌐
Reddit
reddit.com › r/phphelp › how can i json_encode a nested array?
r/PHPhelp on Reddit: How can I json_encode a nested array?
March 2, 2020 -

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.

🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-parse-JSON-with-PHP.php
How to Parse JSON with PHP
PHP cannot read or handle json data, as is. So it converts the json data into something that PHP can understand through the json_decode function. The json_decode() function is a built-in PHP function that converts JSON data into a multidimensional PHP array.
🌐
GitHub
github.com › SimpleMachines › SMF › issues › 3569
TIP: Multi dimensional arrays and json_decode (seem like it have problems with that) · Issue #3569 · SimpleMachines/SMF
January 30, 2016 - Json have problems with multidimensional array they have a key, but no value (empty string or null) If you use a normal json_encode($array) and the a json_decode($json_value) the keys with empty st...
Published   Sep 06, 2016
🌐
Stack Exchange
magento.stackexchange.com › questions › 318327 › how-to-build-a-multidimensional-array-from-the-json-decoded-output
php - How to build a multidimensional array from the Json decoded output? - Magento Stack Exchange
// Array to be built to match JSON decoded version of associative array. $fulfillment_array['orderShipment']['orderLines']['orderLine'] = []; foreach ($fulfillment_records as $this_fulfillment_record) { // Assemble the fulfillment array for Walmart.
🌐
SitePoint
sitepoint.com › php
PHP Multidimensional json array - PHP - SitePoint Forums | Web Development & Design Community
May 4, 2012 - $model = array(); while($e = mysql_fetch_assoc($back)){ $model['weID'] = $e['weID']; $model['size_h'] = $e['size_h']; $model['size_w'] = $e['size_w']; while($h = mysql_fetch_assoc($images)) { $model['images'][] = array( 'imgID' => $h['imgID'], 'imgName' => $h['imgName'] ); while($f = mysql_fetch_assoc($text)){ $model['text'][] = array( 'txtID' => $f['txtID'], 'txtText' => $f['txtText'] ); }; }; }; echo json_encode ($model); mysql_close($con);
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-json_encode-function
PHP | json_encode() Function - GeeksforGeeks
June 17, 2019 - <?php // Declare an array $value = array( "name"=>"GFG", "email"=>"abc@gfg.com"); // Use json_encode() function $json = json_encode($value); // Display the output echo($json); ?> ... {"name":"GFG","email":"abc@gfg.com"} Example 2: This example ...
🌐
SitePoint
sitepoint.com › php
Best practice...json_encode OR serialize? - PHP - SitePoint Forums | Web Development & Design Community
November 3, 2012 - Am trying to store array information gathered from a form. The form is dynamic s the info can include a different number of fields and different names. As such it seems the best way to package the info is in an array or multidimensional array and then store that array into the DB.
🌐
Stack Overflow
stackoverflow.com › questions › 36217265 › php-json-encode-multidimensional-array
PHP json_encode multidimensional array - Stack Overflow
// sample data $data = array ( 'company' => array("99" => 'eeeeee'), 'Naam' => array ("1" => 'werwerew'), 'phone' => array ("4" => 'ewrwerwer'), 'email' => array ("3" => '[email protected]') ); // unnest array, assuming inner level arrays only have one key/value pair: foreach ($data as $key => $row) { $result[$key . ":" . current($row)] = "" . key($row); } // Now convert that flat array to JSON $json = json_encode($result);
🌐
Reddit
reddit.com › r/phphelp › wanting to return json from php as a two dimensional array/nested array using data from a mysqli database
r/PHPhelp on Reddit: Wanting to return JSON from PHP as a two dimensional array/nested array using data from a mySQLi database
March 12, 2021 -

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.

🌐
IncludeHelp
includehelp.com › php › decode-the-json-string-into-a-multi-dimensional-array.aspx
PHP program to decode the JSON string into a multi-dimensional array
The given program is compiled and ... = '[[101,"Amit",5000],[102,"Rahul",7000],[103,"Rohit",8000]]'; $emps = json_decode($json); for ($i = 0;$i < 3;$i++) { for ($j = 0;$j < 3;$j++) { print ($emps[$i][$j] ....
🌐
Coderwall
coderwall.com › p › k-bwtq › the-fastest-way-to-convert-array-to-object-multidimensional
The Fastest Way to Convert Array to Object (multidimensional) (Example)
February 25, 2016 - $data= array( 'base_url' => ... 1 year ago · · Wahyu Kristianto · @robinvdvleuten (object)array(); does not support multidimensional array ·...