Question

I'm working on a website that I make heavy use of json objects. I have a very, very large json object that contains, from what it looks like, dozens of arrays of arrays of arrays of etc...

I've been doing my normal method of just doing:

$obj = json_decode($json,true);
if( $obj == NULL )
    echo "JSON NULL!<br>";
else{                                                                            

    echo "here!!<br>";
    foreach( $obj as $key=>$val ){
        foreach( $val as $k=>$v){

            echo "$k <br>";
        }
    }
}

But the output is not very meaningful and I find it hard to tell what is the parent of what in terms of being able to access the individual items in a $obj["one"]["two"]["three]" manner.

I've looked around quite a bit and there are many examples of using json_decode in foreach arrays, but all the examples I've found target single-depth arrays. Does anyone know of a way to output the contents in a way that would make it easier to tell what contains what?

Ideally something that tabbing, that's the most visually understandable.

Thanks!


Edit: Thanks for the fast replies! I didn't know about the tags. I wish I could select all of them as "best answer"!

Was it helpful?

Solution

$obj = json_decode($json,true);
echo "<pre>".htmlspecialchars(print_r($obj,TRUE))."</pre>\n";

OTHER TIPS

I agree. This might look good to read

 $obj = json_decode($json,true);

 echo "<pre>";
 print_r( $obj );
 echo " </pre>";

This also does the indenting.

I'd suggest something like:

$obj = json_decode($json, true);
echo '<pre>';
echo print_r($obj, true);
echo '</pre>';

I guess you have problem with not knowing how many levels of arrays you have. You could do a recursive function like this:

function echoarray($obj, $i = 0){
    foreach($obj as $key => $val){
        if(isarray($val)) echoarray($val, $i++);
        else echo "$i - $key: $val <br/>";
    }
}

Instead of your original foreach. Variable $i can tell you what level are you on currently. Take this not as a finished code but as a concept, if it suits your needs.

Basically if current $val is array, function echoarray is called again and again, until $val isn't an array anymore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top