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
4
  • 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. Commented Nov 4, 2015 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. Commented Nov 4, 2015 at 18:29
  • Well, sometimes you can't have everything :P Commented Nov 4, 2015 at 18:29
  • This may help as well though: Determine whether an array is associative (hash) or not Commented Nov 4, 2015 at 18:31

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.