fico7489
fico7489

Reputation: 8560

PHP how to detect if JSON decoded part is object or array

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

Upvotes: 1

Views: 4537

Answers (1)

fico7489
fico7489

Reputation: 8560

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

Upvotes: 1

Related Questions