1

I have JSON :

{
    "catalogs": [
        {
            "aa" : "aa",
            "bb" : "bb"
        },
        [
            {
                "cc" : "cc",
                "dd" : "dd"
            },
            {
                "ee" : "ee",
                "ff" : "ff"
            }
        ]
    ]
}

And PHP code :

<?php 

$catalogs = file_get_contents('test.json');
$catalogs = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $catalogs), true );

$catalogs = $catalogs['catalogs'];
foreach($catalogs as $catalog){
    echo gettype($catalog) . '<br/>';
}

Output is:

array
array

But I need something like:

object
array
fico7489
  • 7,931
  • 7
  • 55
  • 89
  • 1
    Don't pass `true` as second argument to `json_decode`? The whole point of this parameter is to return associative arrays instead of objects. If you don't want that, don't pass `true`. – Felix Kling Nov 04 '15 at 18:27
  • ok it works without, but I prefer decoding json as array not as object, but here I will need to decode as object. – fico7489 Nov 04 '15 at 18:29
  • Well, sometimes you can't have everything :P – Felix Kling Nov 04 '15 at 18:29
  • This may help as well though: [Determine whether an array is associative (hash) or not](http://stackoverflow.com/q/5996749/218196) – Felix Kling Nov 04 '15 at 18:31

1 Answers1

1

decoding JSON as object work:

<?php 

$catalogs = file_get_contents('test.json');
$catalogs = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $catalogs) );

$catalogs = $catalogs->catalogs;
foreach($catalogs as $catalog){
    echo gettype($catalog) . '<br/>';
}

Output:

object
array
fico7489
  • 7,931
  • 7
  • 55
  • 89