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 › home › code snippets › php › json_encode of multidimensional array giving different results
JSON_ENCODE of multidimensional array giving different results | W3docs
<?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.
Discussions

How can I json_encode a nested array?
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… More on reddit.com
🌐 r/PHPhelp
16
2
March 2, 2020
php - json_encode() on a multidimensional array - with string keys - Stack Overflow
I am creating an very large multidimensional array using PHP. Each object contains Name, ID, ParentID and Children. Children is an array of more objects in the same format. It is critical I name ... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
PHP json_encode multidimensional array - Stack Overflow
I have an multidimensional array which looks like this: array (size=6) 'company' => array (size=1) 99 => string 'eeeeee' 'Naam' => array (size=1) 1 => string ' More on stackoverflow.com
🌐 stackoverflow.com
March 25, 2016
PHP Multidimensional json array - PHP - SitePoint Forums | Web Development & Design Community
Hi all, hope some one can help me on this?? I need to create the following json data, my PHP code produces this no problems, but I cant seem to loop $back with respect to $images and $text to show all my records in the below json string, I now its due to the way my SQL statement setup, so I ... More on sitepoint.com
🌐 sitepoint.com
0
May 4, 2012
🌐
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 - If the PHP Json Encode is fine, I often find that the problem is UTF8 Encoding. Run a function to encode all of the array values as UTF8 and that should correct it.
🌐
Stack Overflow
stackoverflow.com › questions › 36217265 › php-json-encode-multidimensional-array
PHP json_encode multidimensional array - Stack Overflow
March 25, 2016 - // 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);
🌐
Alvin Alexander
alvinalexander.com › php › php-json_encode-convert-array-to-json-example
A PHP json_encode array conversion example | alvinalexander.com
June 4, 2016 - <?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') ) ); ?>
🌐
SitePoint
sitepoint.com › php
PHP Multidimensional json array - PHP - SitePoint Forums | Web Development & Design Community
May 4, 2012 - Hi all, hope some one can help me on this?? I need to create the following json data, my PHP code produces this no problems, but I cant seem to loop $back with respect to $images and $text to show all my records in the below json string, I now its due to the way my SQL statement setup, so I ...
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 ...
🌐
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.
🌐
Scout APM
scoutapm.com › home › blog › php json_encode: serialize php objects to json
PHP Json_encode: Serialize PHP Objects to JSON | Scout Monitoring
May 1, 2020 - We can create a Multidimensional array to store a list of books for our library example. Let’s create one and encode that into JSON. <?php $books = array( array("id"=>101, "label"=>"Lorem Ipsum"), array("id"=>102, "label"=>"Dolor sir amet"), array("id"=>103, "label"=>"Lorem Ipsum dolor"), ); echo json_encode($books); ?>
Top answer
1 of 2
6

If you can access the images key, then:

<?php
$json = <<<JSON
{
    "title":"A Title Here",
    "images":[
        {
            "coverType":"fanart",
            "url":"some_random_file_here.jpg"
        },
        {
            "coverType":"banner",
            "url":"another_random_file_here.jpg"
        },
        {
            "coverType":"poster",
            "url":"yet_another_random_file_here.jpg"
        }
    ]
}
JSON;

$json = json_decode($json);
print_r($json);

foreach ($json->images as $img)
{
    if ( $img->coverType == "banner" )
    {
        echo 'Image Cover Type: ' .$img->coverType .'<br/>';
        echo 'URL: ' .$img->url .'<br/>';
    }
}
?>

Gives:

Image Cover Type: banner

URL: another_random_file_here.jpg

UPDATE:

The JSON file you link to seems invalid, missing braces after each series. Here's the corrected JSON, and code:

<?php
$json = <<<JSON
[
{
    "series": {
      "title": "Brooklyn Nine-Nine",
      "images": [
        {
          "coverType": "fanart",
          "url": "http://thetvdb.com/banners/fanart/original/269586-15.jpg"
        },
        {
          "coverType": "banner",
          "url": "http://thetvdb.com/banners/graphical/269586-g3.jpg"
        },
        {
          "coverType": "poster",
          "url": "http://thetvdb.com/banners/posters/269586-13.jpg"
        }
      ],
      "year": 2013
    }
},
{
    "series": {
      "title": "The Middle",
      "images": [
        {
          "coverType": "fanart",
          "url": "http://thetvdb.com/banners/fanart/original/95021-16.jpg"
        },
        {
          "coverType": "banner",
          "url": "http://thetvdb.com/banners/graphical/95021-g14.jpg"
        },
        {
          "coverType": "poster",
          "url": "http://thetvdb.com/banners/posters/95021-8.jpg"
        }
      ],
      "year": 2009
    }
},
{
    "series": {
      "title": "New Girl",
      "images": [
        {
          "coverType": "fanart",
          "url": "http://thetvdb.com/banners/fanart/original/248682-43.jpg"
        },
        {
          "coverType": "banner",
          "url": "http://thetvdb.com/banners/graphical/248682-g20.jpg"
        },
        {
          "coverType": "poster",
          "url": "http://thetvdb.com/banners/posters/248682-14.jpg"
        }
      ],
      "year": 2011
    }
}
]
JSON;

$json = json_decode($json);
// echo '<pre>' .print_r($json, 1) .'</pre>';

foreach ($json as $item)
{
    echo 'Title: ' .$item->series->title .'<br/>';
    foreach ($item->series->images as $img)
    {
        if ( $img->coverType == "banner" )
        {
            echo 'Image Cover Type: ' .$img->coverType .'<br/>';
            echo 'URL: ' .$img->url .'<br/>';
        }
    }
}
?>

Gives:

Title: Brooklyn Nine-Nine Image Cover Type: banner URL: http://thetvdb.com/banners/graphical/269586-g3.jpg

Title: The Middle Image Cover Type: banner URL: http://thetvdb.com/banners/graphical/95021-g14.jpg

Title: New Girl Image Cover Type: banner URL: http://thetvdb.com/banners/graphical/248682-g20.jpg

2 of 2
0

Suppose this is the variable jsondecoded, $json[images][1]->coverType;

🌐
ReqBin
reqbin.com › code › php › 0kvtdskv › php-array-to-json-example
How do I convert PHP Array to JSON?
To convert a PHP array to JSON data string, you can use the json_encode($value, $flags, $depth) function.
🌐
Stack Overflow
stackoverflow.com › questions › 21765610 › json-encode-with-a-multidimensional-array
json_encode with a multidimensional array
The next thing to do is to iterate it 3 times, one each for your three output variables and produce the 2D array for each one. Then after you have those, you can use PHP to write out the JavaScript and call json_encode() on the individual arrays.
🌐
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
September 6, 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...
Author: SimpleMachines
🌐
Stack Overflow
stackoverflow.com › questions › 30832985 › multidimensional-array-json-encoded
php - Multidimensional array json_encoded - Stack Overflow
Copyelseif($request == "revenues"){ // Output Revenues per day from nexus store $revenues = array(); $revenues["dates"] = array(); $revenues["amount"] = array(); $sql = "select i_total as revenue, date(FROM_UNIXTIME(i_date)) as date FROM nexus_invoices WHERE i_status='paid' GROUP BY date(FROM_UNIXTIME(i_date)) ORDER BY i_date DESC LIMIT 0,10"; $rows = $db->query($sql); foreach($rows as $row){ $revenues["dates"][] = $row['date']; $revenues["amount"][] = floatval($row['revenue']); } //$revenues["amount"] = [1,5,5.5,5.4,5.8,6,8,9,13,12,10,11.5,9,8,5,8,9]; echo json_encode($revenues); }
🌐
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.